Shell scripting for system administrators: the basics
For system administrators shell scripting can be a very useful way to drastically improve workflow. Join Swayam Prakasha to find out how you can employ some fundemental tips and techniques to make your life easier…
Look at the command ‘ls –l | grep file’. Here, the long listing of the current directory is piped to the grep command that searches for a specific pattern and displays the result on stdout. The screenshot in the gallery titled ‘Figure 1‘ shows this procedure.
We can initialise the variables within a shell script in this format:
Please note that we cannot have spaces on either side of the equals sign. One can reference a variable as ‘$name’.
Let us consider a shell script to understand more on this:
[sourcecode language=”bash”][root@localhost ~]# cat script_1.sh
echo $msg1 $msg2
And let us try to execute this script:
[sourcecode language=”bash”][root@localhost ~]# ./script_1.sh
-bash: ./script_1.sh: Permission denied
Well, we got into an error here as the script does not have the required permission to execute. Now we need to change the permission using the ‘chmod’ command at the command prompt. Note that it is enough to provide execute permission to our script with the chmod command.
After changing the permission, the script will execute successfully and display ‘Welcome LUD’.
We can also execute a shell script in another way as given below:
[sourcecode language=”bash”][root@localhost ~]# sh script_1.sh
Take a look at the screenshot titled ‘Figure 2‘ in the gallery on page 1 for an illustration of this.
If we need to assign a string to a variable and the string contains spaces, we need to enclose the string in double quotes:
[sourcecode language=”bash”]msg1 = “Welcome to LUD”
We can also have arithmetic expansions within a shell script. And they take the following format:
[sourcecode language=”bash”]$ ((expansion))
The screenshot titled ‘Figure 3‘ explains one example of arithmetic expansion. You can find it in the gallery on page 1.