Advanced Bash Scripting

From Colwiki.org

Jump to: navigation, search


Outcomes

In this module you will learn about:
  1. The bash environment and bash scripting essentials
  2. Logical Evaluation and Loops
  3. Handling User Input
  4. Working with numbers


Contents

Variables

When you type a command at the prompt the bash shell will use the PATH variable to find which executable on the system you want to run. You can check the value of path using the echo command:

  echo $PATH
  /usr/bin:/bin:/usr/sbin:/usr/X11R6/bin:/usr/local/bin:/sbin/:/usr/local/sbin/

In fact many variables are needed by the shell to accommodate for each user’s environment. For example PWD, HOME, TERM and DISPLAY are such variables.

To initialise and declare a variable the syntax is as follows:

  VARIABLE=VALUE

Remember not to put any spaces around the ‘=’ sign. Once a variable is declared and initialised it can be referenced by using the dollar symbol in front as here:

  echo $VARIABLE

When a shell session is started a number of configuration files are read and most of the variables are set. To free a variable from its current value use unset.

Configuration files One can distinguish configuration files which are read at login time and configuration files which are read for each new bash session.

Login configuration files: The files which are read at login are /etc/profile and ~/.bash_profile (bash will look for alternative files too such as ~/.profile). Next bash will read it’s runtime control files ~/.bashrc and (if it exists) /etc/bashrc.

The bashrc files: These files are read each time a new shell session is launched (such as a new xterm). The files are /etc/bashrc and ~/.bashrc. Alias and functions can be saved in the ~/.bashrc

Function syntax:

  function-name  ()
  {
   command1;
   command2;
  }

You can test which files are being read by adding an echo Profile line in /etc/profile, the type:

bash No profile is read, you shouldn’t see anything

bash -login This forces bash to act as a login bash, the word Profile should show up.

The following commands control the way bash starts:

  bash -norc
  bash -noprofile

Notice that any new bash session will inherit the parent’s global variables defined in /etc/profile and ~/.bash_profile.

Scripting Essentials

A shell script is a list of instructions saved in a flat file. Only two things are necessary.

  • The script’s first line must be #!/bin/bash (for a bash script)
  • The file must be readable and executable (with 755 permission for example)

If these lines are not present it is possible to run the script program by typing

  bash program-name

Passing variables to the script

Variables entered at the command line are referenced inside the script as $1 for the first argument, $2 for the second, etc …

Example script, mycat:

#!/bin/bash
  cat $1

This script is expecting one argument, a file, and will display the content of the file using cat. To run this script on the lilo.conf file, you would run:

  ./mycat /etc/lilo.conf

Another way of passing variables to a script is by letting the script prompt the user for input interactively. This is achieved using the read command. The default name of the read variable is REPLY. Here is the modified script:

Interactively passing:

  #!/bin/bash
  echo -n "Which file shall I display ?"
  read
  cat $REPLY

or

  read -p “File to display: “ FILENAME
  cat $FILENAME

Special Variables Special variables can only be referenced and are automatically set by bash. These are the most common special variables you will encounter: $* List of all variables entered at the command line $# Number of arguments entered at the command line $0 The name of the script $! PID of the most recent background command $$ PID of the current shell $? Exit code of the last command For the positional parameters $1, $2 etc … there is a shift operator which renames each parameter in a cyclic way as follows.

  $2 becomes $1
  $3 becomes $2  … etc 

This can be summarised as $(n+1)  $n

Logical evaluations

Logical statements are evaluated with the test command or the brackets [ ]. In both case the result is stored in the $? variable such that:

  if the statement is true then 	$? is 0		
  if the statement is false then	$? is not 0

Here are some examples to illustrate:

One can evaluate more than one statement at a time using the || (OR) and && (AND) logical operators on the command line. For example we could test if /bin/bash is executable and in /etc/inittab exists:

  test -x /bin/bash && test /etc/inittab
  [ -e /bin/kbash ] || [ -f /etc/passwd ]

This is the same as using the flags -o and -a within the test operator for example

 test -x /bin/bash -a -f /etc/inittab
 [ -e /bin/kbash -o -f /etc/passwd ]

Logical evaluations

if then loop Syntax:

      if	CONDITION ; then
  		   command1

command2 fi

  #!/bin/bash
  if [ -x /bin/bash ] ; then
  echo “The file /bin/bash is executable”
  fi

if then else

Syntax:	if 	CONDITION ; then

command1 command2 else command3

              fi

while loop

Syntax:	while CONDITION is true; do

command done

Example: Aligne 10 hashes (#) then exit

#!/bin/bash
COUNTER=0
while [ $COUNTER -lt 100 ]; do
       echo  -n "#"

sleep 1

       let COUNTER=COUNTER+1
done

Until loop

Syntax:	until CONDITION is false; do

command done

Example: Same as above, notice the C style increment for COUNTER

#!/bin/bash
COUNTER=20
until [ $COUNTER -lt 10 ]; do
       echo -n "#"
       sleep 1
       let COUNTER-=1
done


for loop

Syntax	for VARIABLE in SET; do

command done

Example: For example the set 'SET' can be the lines of a file

#!/bin/bash
for line in `cat /etc/lilo.conf`; do
     IMAGE=$(echo $line | grep image) 

if [ “$IMAGE” != “” ]; then echo Kernel configured to boot: $line

fi
done

Expecting user input

We assume that the script is waiting for user input, depending on the answer; the rest of the program will execute something accordingly. There are two possible ways to achieve this: select and case. Using case

Syntax:	case $VARIABLE in

CHOICE command ;; CHOICE command ;; esac Using select

Syntax:	select VARIABLE in SET; do

if [ $VARIABLE = CHOICE ]; then command fi if [ $VARIABLE = CHOICE ]; then command fi done

Working with Numbers

While shell scripts seamlessly handle character strings, a little effort is needed to perform very basic arithmetic operations. Binary operations

  expr 7 + 3; expr 2 \* 10; expr 40 / 4; expr 30 – 11

Adding or multiplying numbers together can be achieved using either expr or the $(( )) construct.

Example:

  $((7+3)); $((2*10)); $((40/4)); $((30-11))

Comparing values

Test operators:


Summary

In many Linux distributions, tasks are automated by shell scripts. It is important for you as an administrator to know how to do shell scripting yourself.

In this module you have learned the basic ingredients to use in a shell script. The module was in no way meant to be a complete overview of all that can be done with shell script but gave you what you need to be able to start. You can read more about bash scripting from: http://linuxreviews.org/beginner/Bash-Scripting-Introduction-HOWTO/en/index.html and http://tldp.org/LDP/abs/html/





Assignment

grep test) ]; then
  echo The PID of the interpreter is: $$  
  Else
  echo The PID of the interpreter is: $$
  Fi
  1. Set the permissions to 755 and test the following commands
  test_shell
  ./test_shell
  bash test_shell
  . test_shell
  source test_shell
  exec ./test_shell



Image:somerights20.png This work is licenced under a Creative Commons - By Attribution Licence - Share Alike License.

Personal tools
News & Events