Shell Script – Introduction to shell script

Shell Script – Introduction to shell script

Basically, a shell script is a text file with Unix commands in it.

Shell scripts usually begin with a #! and a shell name

  • – For example: #!/bin/sh
  • – If they do not, the user’s current shell will be used

Any Unix command can go in a shell script

  • – Commands are executed in order or in the flow determined by control statements.

Different shells have different control structures

  • – The #! line is very important
  • – We will write shell scripts with the Bourne shell (sh)

Why write shell scripts?

  • – To avoid repetition:

If you do a sequence of steps with standard Unix commands over and over, why not do it all with just one command?

  • – To automate difficult tasks:

Many commands have subtle and difficult options that you don’t want to figure out or remember every time.

Assigning Command Output to a Variable

  • Using backquotes, we can assign the output of a command to a variable:

#!/bin/sh

files=`ls`

echo $files

 

  • Very useful in numerical computation:

#!/bin/sh
value=`expr 12345 + 54321`
echo $value

Using expr for Calculations

  • Variables as arguments:

% count=5
% count=`expr $count + 1`
% echo $count
6
– Variables are replaced with their values by the shell!

  • expr supports the following operators:

– arithmetic operators: +,-,*,/,%
– comparison operators: <, <=, ==, !=, >=, >
– boolean/logical operators: &, |
– parentheses: (, )
– precedence is the same as C, Java