Friday 18 November 2011

Basic Shell Scripting

Command Line Arguments:

Argument
Functionality
$#
Represents the parameter count. Useful for controlling loop constructs that need to process each parameter
$@
Expands to all the parameters separated by spaces. Useful for passing all the parameters to some other function or program
$*
Contains the string of all arguments (positional parameters) on the command line
The variable $@ is the same as $* except when enclosed in double quotes. Then, each argument contained in $@ is double quoted.
$-
Expands to the flags (options) the shell was invoked with. Useful for controlling program flow based on the flags set # echo $-
$$
Expands to the process id of the shell innovated to run the script/ current shell. Useful for creating unique temporary filenames relative to this instantiation of the script
$?
contains the exit status of the last command or shell program
$!
Contains the process ID number of the last command sent to the background. $ kill -9 $!
$0
Contains the name of the command (process) currently being executed
The variables $#,$* and $@ also change with the shiftcommand.
Once a shift is performed, the first parameter is discarded. The $# variable is decremented, and the $* and $@ variables are updated.


Variables:

Assign a variable to a value
For string with space use "" $ var1="Hello World"
Read only variables
$ readonly variable_name
Assign variable from read line
$ read fname lname # Read 2 values separated by Space #"AA BB" "CC DD"/AA BB
Assign NULL to a variable
$ name=/ $ name=''/ $ name=""/ $ unset varname


Parameter substitution formats:

Substitution
Definition
Purpose
${parameter:-value}
If parameter exists and isn't null, return its value; otherwise return value
Returning a default value if the variable is undefined. $ echo ${var1:-$HOME}
${parameter:=value}
If parameter exists and isn't null, return its value; otherwise set it to value and then return its value
Setting a variable to a default value if it is undefined. $ echo ${var1:=$HOME}
${parameter:+value}
If parameter exists and isn't null, return value; otherwise return null.
Testing for the existence of a variable.
${parameter:?value}
If parameter exists and isn't null, return its value; otherwise print parameter: followed by message and abort the current command or script. Omitting message produces the default message parameter null or not set.
Catching errors that result from variables being undefined.


Command Substitution:
  • $(command)
  • `command`
Arithmetic Expansion:
  • $((expression))
  • echo $((1 + 3 + 4))
Relational Operators(works for numerical values 10, 20 or “10”, “20”):
  • -eq EQUALS TO
  • -ne NOT EQUALS TO
  • -gt GREATER THAN
  • -lt LESS THAN
  • -ge GRATER THAN OR EQUALS TO
  • -le LESS THAN OR EQUALS TO
Boolean Operators:
  • ! NOT
  • -o OR
  • -a AND
String Operators:
  • = EQUALS TO # [ $a = $b ]
  • != NOT EQUALS TO # [ $a != $b ]
  • -z RETURNS TRUE FOR ZERO LENGTH STRING # [ -z $a ]
  • -n RETURNS TRUE FOR NON-ZERO LENGTH STRING # [ -n $a ]
  • str RETURNS TRUE FOR NON-EMPTY STRING # [ $a ]
File Test Operators:
Operator
Description
-a file
True if file EXISTS
-b file
TRUE if file is a block special file
-c file
TRUE if file is a character special file
-d file
TRUE if file is a directory
-e file
TRUE if file exists. Is TRUE even if file is a directory but exists
-f file
TRUE if file is an ordinary file as opposed to a directory or special file
-g file
TRUE if file has its group ID (SGID) bit set
-k file
TRUE if file has its sticky bit set
-p file
TRUE if file is a named pipe
-t file
TRUE if file descriptor is open
-u file
TRUE if file has its user id (SUID) bit set
-r file
TRUE if file is readable/ read permission
-w file
TRUE if file is writable/ write permission
-x file
TRUE if file is execute/ execute permission
-s file
TRUE if file has size greater than 0
-O file
TRUE if you own file
-G
TRUE file your group id is same as file's
file1 -nt file2
TRUE if file1 is newer than file2
file1 -ot file2
TRUE if file1 is older than file2


Pattern Matching:
  • *     Zero or More Characters, Except a Leading dot 
  • ?     Any Single Character, Except a Leading dot
  • []    Defines a Class of Characters ( - for Range, ! to Exclude)

If Statement:
if [ "$1" = "1" ]
then
echo "The first choice is nice"
elif [ "$1" = "2" ]
then
echo "The second choice is just as nice"
else
echo "I see you were wise enough not to choose"
echo "You win"
fi

Do...While:
count=$1 # Initialise count to first parameter
while [ $count -gt 0 ] # while count is greater than 10 do
do
echo $count seconds till supper time!
count=$(expr $count -1) # decrement count by 1
sleep 1 # sleep for a second using the Unix sleep command
done

For:
fruitlist="Apple Pear Tomato Peach Grape"
for fruit in $fruitlist
do
if [ "$fruit" = "Tomato" ] || [ "$fruit" = "Peach" ]
then
echo "I like ${fruit}es"
else
Unix Shell Scripting Tutorial
echo "I like ${fruit}s"
fi
done

Case:
case $1
in
1) echo 'First Choice';;
2) echo 'Second Choice';;
*) echo 'Other Choice';;
esac

Functions:
name() {
commands
}

·         For any local function variable we write: local value=4

#!/bin/sh
inc() { # The increment is defined first so we can use it
echo $(($1 + $2)) # We echo the result of the first parameter plus the second parameter
}
if [ "$1" "" ] || [ "$2" = "" ] || [ "$3" = "" ]
then
Unix Shell Scripting Tutorial
echo USAGE:
echo " counter startvalue incrementvalue endvalue"
else
count=$1 # Rename are variables with clearer names
value=$2
end=$3
while [ $count -lt $end ] # Loop while count is less than end
do
echo $count
count=$(inc $count $value) # Call increment with count and value as parameters
count=`inc $count $value`
done # so that count is incremented by value
fi

·         Import functions from a script called common.sh in DIRECTORY

#!/bin/sh
. ./common.sh

if [ "$1" = "" ]; then
echo USAGE:
echo "sh test.sh type"
exit
fi

if `validtype $1`; then
echo Valid type
else
echo Invalid type
fi

Here is common.sh:
#!/bin/sh
validtype() {
if [ "$1" = "TYPEA" ] || [ "$1" = "TYPEB" ] || [ "$1" = "TYPEC" ] || [ "$1" = "TYPED" ] || [ "$1" = "TYPEE" ];
then
exit 0
else
exit 1
fi
}

1 comment: