Table of contents
- 1. What is Script?
- 2. What is Echo?
- 3. How to execute any script file?
- 4. How to Create a folder and file using scripting.
- 5. What are Variables and Arguments?
- 6. Script to check any file or directory is present or not
- 7. What are Loops in Scripting?
- 8. How to get the list of the files in a directory in a shell script?
- 9. echo "Now I know how to write Scripts"
1. What is Script?
In Simple terms, a shell script is a file that consists of a set of commands. The shell reads the file and carries out the commands as they have been entered into the command line.
Normally the shell script has the file extension .sh and it always starts with #!/bin/bash which is also known as the shebang line.
We use vi/vim editor to write our scripts
2. What is Echo?
The Echo command is used to display a line of text that has been passed as an argument.
3. How to execute any script file?
To execute the shell script file we can use:
bash <filename> OR ./<filename> OR sh <filename>
Before executing any file we need to make that particular file executable and for that, we can use chmod (change mode permissions).
4. How to Create a folder and file using scripting.
#!/bin/bash
mkdir subhankar_devops
cd /home/ubuntu/my_scripts/subhankar_devops
touch subh.txt
echo "I know Scripting" > subh.txt
5. What are Variables and Arguments?
Variables are used to store or pass values in a Script where as Arguments are parameters that are passed to a script while executing them in the bash shell
Variable:
#!/bin/bash
echo "enter the name"
read username
echo "enter your roll no"
read rollno
echo "My name is $username and my roll no is $rollno"
6. Script to check any file or directory is present or not
#!/bin/bash
echo "enter the file name"
read filename
echo "checking if $filename exists...."
if [ -f $filename ]
then
echo "$filename exist"
else
echo "$filename does not exist"
fi
echo "enter directory name"
read directory
echo "checking if $directory exists...."
if [ -d $directory ]
then
echo "$directory exist"
else
echo "$directory does not exist"
fi
7. What are Loops in Scripting?
Loops allow us to take a series of commands and keep re-running them until a particular situation is reached.
Types: For loop, while loop, do-while loop
#!/bin/bash
for num in {1..10}
do
echo "$num"
done
8. How to get the list of the files in a directory in a shell script?
#!/bin/bash
for filename in $1/* ----------/* denotes all the file (/home/ubuntu)
do
echo "$filename"
done