Bash scripting Notebook {part 1}
Table of contents:
- what is shell scripting?
- Types of shells.
- BASH
- Bash utility commands
- Math in Shell.
- Conditional statements and loops
- Running bash script
Shell scripting
A shell script is little more than a list of commands that are run in sequence. Conventionally, a shell script should start with a line such as the following:
#!/bin/bash
This line is also called as shebang which is nothing but the absolute path to the Bash interpreter. It consists of a number sign and an exclamation point character (#!), followed by the full path to the interpreter such as /bin/bash. All scripts under Linux execute using the interpreter specified on a first line.
Types of shells:
Shell Startup Process — BASH/SH/ZSH Startup Process.
check valid shells on Linux machine
cat /etc/shells
bash(/bin/bash)- Bourne Again Shell
csh(/bin/csh)-c shell
dash(/bin/dash)- Debian Almquist shell
ksh(/bin/ksh)-Korn Shell
zsh(/bin/zsh)- Z shell
Check the current shell:
echo $SHELL
When a terminal is opened, a prompt is available which usually
has the following format:
username@hostname$
Or:
root@hostname #
or simply as $ or #.
$ represents regular users and # represents the administrative user root. Root is the most privileged user in a Linux system.
When a shell is started, it initially executes a set of commands to define various settings such as prompt text, colors, and much more. This set of commands are read from a shell script at
~/.bashrc or ~/.bash_profile :- for login shells
~/.bash_history file:- maintains a history of commands run by the user
Example: checking for superuser.
if [ $UID = 0 ];then echo root;else echo not root;fi
BASH: Bourne Again SHell.
Bash utility commands:
In Bash, each command or command sequence is delimited by using a semicolon or a new line. For example:
$ cmd1 ; cmd2#This is equivalent to:$ cmd1$ cmd2
Command Substitution
Brace expansion works as follows: $(commands)
expands to the output of commands This permits nesting, so commands can include brace expansions
Backtick expansion expands `commands`
to the output of commands
X=`expr 3 \* 2 + 4` # expr evaluate arithmatic expressions. man expr for details.
echo "$X"
color outputs
echo -e “\e[1;31m This is red text \e[0m”echo -e "\e[1;42m Green Background \e[0m"
Redirection outputs:
difference between > and >>
> :- It truncates the file. contents will be emptied before writing and write only current contents.
>> :- It append text to a file.
alias
syntax:
$ alias new_command='command sequence'
Giving a shortcut to the install command, apt-get install, can be done as follows:
$ alias install='sudo apt-get install'
The alias command is temporary; aliasing exists until we close the current terminal only. To keep these shortcuts permanent, add this statement to the ~/.bashrc file. Commands in ~/.bashrc are always executed when a new shell process is spawned:
$ echo ‘alias cmd=”command seq”’ >> ~/.bashrc
read
#The following statement will read n characters from input into the variable_name variable:read -n number_of_chars variable_name
$ read -n 2 var
$ echo $var#Read a password in the nonechoed mode as follows:
read -s var#Display a message with read using:
read -p "Enter input:" var#Read the input after a timeout as follows:
read -t timeout var
$ read -t 2 var
Math with the shell
the commands:
let, (( )), and []. The two utilities expr and bc are also very helpful in performing advanced operations.
#!/bin/bash
no1=4;
no2=5;
let result=no1+no2
echo $resultresult=$[ no1 + no2 ]result=`expr 3 + 4`
result=$(expr $no1 + 5)no=54;
result=`echo "$no * 1.5" | bc`
echo $result #output 81.0
Decimal places scale with bc:
echo “scale=2;3/8” | bc #output 0.37
Arrays and associative arrays
array_var=(1 2 3 4 5 6)#Values will be stored in consecutive locations starting from index 0.Alternately, define an array as a set of index-value pairs as follows:array_var[0]="test1"
array_var[1]="test2"
array_var[2]="test3"#Print the contents of an array at a given index using the following commands:echo ${array_var[0]} #output test1index=5
echo ${array_var[$index]} #output test6#Print all of the values in an array as a list using the following commands:echo ${array_var[*]}
#output test1 test2 test3 test4 test5 test6Alternately, you could use:$ echo ${array_var[@]}
associative array:
$ declare -A ass_array
#After the declaration, elements can be added to the associative array using two methods as follows:ff By using inline index-value list method, we can provide a list of index-value pairs:$ ass_array=([index1]=val1 [index2]=val2)ff Alternately, you could use separate index-value assignments:$ ass_array[index1]=val1
$ ass_array'index2]=val2For example, consider the assignment of price for fruits using an associative array:$ declare -A fruits_value
$ fruits_value=([apple]='100dollars' [orange]='150 dollars')
Conditionals, if/then/elif
The syntax is as follows:
if condition
then
statement1
statement2
..........
fi
Sometimes, you may wish to specify an alternate action when the condition fails. Here's how it's done.
if condition
then
statement1
statement2
..........
else
statement3
fi
alternatively, it is possible to test for another condition if the first "if" fails. Note that any number of elifs can be added.
if condition1
then
statement1
statement2
..........
elif condition2
then
statement3
statement4
........
fi
Loops
Loops are constructions that enable one to reiterate a procedure or perform the same procedure on several different items. There are the following kinds of loops available in bash
- for loops
- while loops
- repeat
- until loop
for loop :
example: for printing IP range from 1to 30 at the local network.
for i in {1..30}; do echo 192.168.0.$i ;done
for i in `seq 1 30`; do echo 192.168.0.$i ; done
c-type syntax:
for ((x = 0 ; x <= 100 ; x++)); do
echo "Counter: $x"
done
while loop
#!/bin/bash
X=0
while [ $X -le 20 ]
do
echo $X
X=$((X+1))
done
Using an until loop:
A special loop called until is available with Bash. This executes the loop until the given condition becomes true. For example:
x=0;
until [ $x -eq 9 ]; # [ $x -eq 9 ] is the condition
do
let x++; echo $x;
done
repeat
repeat()
{
while true
do
$@ && return
done
}
Or, add this to your shell’s rc file for ease of use:
repeat() { while true; do $@ && return; done }
Running Bash Scripts
The script should have execute permission for the correct owner for running. we can change the permission using chmod
chmod u+x script.sh
Numeric mode: