Official website for Linux User & Developer
FOLLOW US ON:
Aug
13

Shell scripting for system administrators: the basics

by Swayam Prakasha

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.

Variables
We can initialise the variables within a shell script in this format:

name=name

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:

[root@localhost ~]# cat script_1.sh
#!/bin/sh

msg1=Welcome
msg2=LUD
echo $msg1 $msg2

And let us try to execute this script:

[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:

[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:

msg1 = “Welcome to LUD”

Arithmetic expansions
We can also have arithmetic expansions within a shell script. And they take the following format:

$ ((expansion))

The screenshot titled ‘Figure 3‘  explains one example of arithmetic expansion. You can find it in the gallery on page 1.

twitter follow us
Pages: 1 2 3 4 5 6
  • Tell a Friend
  • Follow our Twitter to find out about all the latest Linux news, reviews, previews, interviews, features and a whole more.