
Shell Script can be very helpful in automating day to day tasks.
If you have exposure to programming then getting into the Shell scripting is fairly easy but can sometimes be tricky. Specially due to all the gimmicks it has under its sleeves, which are intended to make tasks easier(and they do) but takes a programmer, who has no prior knowledge of shell scripting by surprise.
This article is more about how to get things done in Shell Script when you already have exposure to other programming language but can be helpful for anyone starting out with Shell scripting.
In case you have no prior experience in scripting or programming, check out the article Think Programming to understand why these concepts exists.
Here’s a quick reference to the constructs present in Shell Scripting to get you to understand and write scripts quickly.
#!/bin/sh – Tells the interpreter that the script to be executed by Bourne shell.
# – to comment a line in a bash shell.
- Variables
- for Loop
- while Loop
- if-else Statements
- CASE Statement
- Arrays
- Array Operations
- Array Iteration
- Functions
- Defining Functions
- Passing arguments to a function
- Returning values from functions
- Conditional Flags and Comparisons
- Miscellaneous
Variables
Naming a variable – In Caps : MY_VAR
Accessing a variable – $MY_VAR
- – It is better to use ${MY_MSG} compared to $MY_MSG
- – If you try to use the variable which doesn’t exist then it prints an empty value
- – If the values of the variables are changed in a script, then the value outside of the script will not be changed. You need to source the script for changes to take effect. run the script as $ . ./myscript.sh
- – To create a dynamic variable name : ${VAR_A}_item
- – When using strings as values, use quotes.
Reserved Variables
- – $0 – holds the base name of the program
- – $1 …. $9 – are the parameters passed to the program
- – $@ – lists all parameters
- – $# – number of parameters script was called with
- – $? – Another special variable is $?. This contains the exit value of the last run command.
- – $$ — variable is the PID – Process IDentifier of the currently running shell.
- – $! — The $! variable is the PID of the last run background process. This is useful to keep track of the process as it gets on with its job.
- – Note that the value of $0 changes depending on how the script was called.
Escape Character
- – \ Is treated as escape character in shell scripts when used with double quotes.
- – If you want to escape *, ” etc. then use \ to escape
- – Character $, `, and \ are interpreted by the shell even when they are inside the double quotes.
for Loop
For loop will loop over any kind of data .. it does not have to be restricted to a particular type of data type.for i in 1 2 hello
do
echo $i
done
while Loop#!/bin/sh
VAR_A=1
while [ ${VAR_A} -ne 5 ]
do
VAR_A=`expr ${VAR_A} + 1`
echo hello + ${VAR_A}
done
- [ ] – denotes the test condition, your exit condition goes in between.
- Spaces are important : <space>[<space> <exit condition> after <space>]<space>
- Using : with while instead of exit condition, always evaluates to true. replace 3rd line with while :
if-else Statementsif [ … ]
then
#do something
else
#do something else
fi
You can also shorten the syntax by writing first two line as shown below.if [ … ]; then
#do something
else
#do something else
fi
Using elifif [ … ]; then
# do something
elif [ … ]; then
# do something
else
#do something
fi
Again Spaces are important : <space>[<space> <condition> after <space>]<space>
You can also use the condition logic in the following manner.[ $Y -gt 0 ] && echo "Y isn't zero" || echo "Y is greater than zero"
CASE Statementcase $INPUT_STRING in
one)
echo 1
;;
two)
echo 2
;;
*)
echo "no match found"
;;
esac
Arrays
ANIMALS=( ‘cat’ ‘dog’ ‘rat’ )
- – echo ${ANIMALS[0]} – prints cat
- – echo ${ANIMALS[@]} – prints all animals in list separated by space
- – echo ${#ANIMALS[@]} – prints number of element
- – echo ${#ANIMALS[2]} . – prints length of second element
Array Operations
- – ANIMALS+=( ‘cow’ ) – add an item to the list.
- – ANIMALS=(“${ANIMALS[@]}” “cow”) – another way to add an item
- – ANIMALS=( ${ANIMALS[@]/dog/} ) – remove an item by name
- – unset ANIMALS[1] – remove item by index
- – ANIMALS=(“${ANIMALS[@]}” “${BIRDS[@]}”) – concatenate two lists
Array Iterationfor i in "${ANIMALS[@]}"; do
echo $i
done
Functions
Defining Functionssamplefunc() {
echo "hello world"
}
You can also define a function as shown below:function samplefunc() {
echo "hello world"
}
Passing arguments to a functionsamplefunc() {
echo "hello $1"
}
samplefunc "world"
- – Here the “world” will be passed as argument to the function, and to use it in a function use $1, $2 etc. depending on the number of argument.
- – Use $# to get the number of arguments
- – Use $* to get all the arguments
- – Use $@ to get all arguments from a list
Returning values from functionsfunction samplefunc() {
MY="world"
echo $MY
}
output="$(samplefunc)"
echo $output
To raise/return an error from a function use return 1
Conditional Flags and Comparisons
- – [ -n STRING ] – not empty string
- – [ -z STRING ] – empty string
- – [ STRING1 = STRING2 ] – equal to
- – [ STRING1 != STRING2 ] – not equal to
- – [ int1 -eq int2 ] – equal to
- – [ int1 -ne int2 ] – not equal
- – [ int1 -gt int2 ] – greater than
- – [ int1 -lt int2 ] – less than
- – [ int1 -le int2 ] – less than or equal to
- – [ int1 -ge int2 ] – greater than or equal to
- – [ file1 -ot file2] – older than
- – [ file1 -nt file2] – newer than
Miscellaneous
- – \ – or splitting lines for better readability
- – read VAR_A – read input value for VAR_A
- – `<some command>` – runs in a sub shell. You can use it to insert command within double quotes
- – IFS – Internal Field Separator – default is Space, New line and Tab
- – -en – using -en to echo tells it to exclude the newline
- – :- – to specify a default value to be used. If the value of the variable is not set. ${VAR_A:-abc} – if the VAR_A is not set then it will be set to abc.
- – := – for setting and using a default value to a variable
- – shift – shifts all arguments to left by one place. $2 becomes $1 , and original $1 gets deleted.
- – $((VAR_A++)) – increases the value of VAR_A by 1
- – $((VAR_A–)) – decreases the value of VAR_A by 1
- – export $VAR_A – makes VAR_A available to all the new subprocesses
- – #!/bin/sh -x – enables debugging in your script
- – #!/bin/sh -n – checks the syntax of script without running any commands
If you want to get in depth knowledge about shell script, then refer https://www.shellscript.sh/
If you want to know more about shell scripts from the interview point of view then refer this article from medium.
Please leave your feedback in comments section. Subscribe to the blog to get the notifications on new posts.