Writing Readable Bash Scripts
#!/bin/bash set -u set -e set -o pipefail function is-even { if [[ $(($1 % 2)) -gt 0 ]] then return 1 else return 0 fi } function epoch { date +"%s" } if is-even $(epoch) then echo "Even epoch" else echo "Odd epoch" fi =============================================== set -u will cause the script to fail if you’re trying to reference a variable that hasn’t been set. The default behavior will just evaluate the variable to the empty string. set -e will cause the script to exit immediately if a command fails. The default behavior is to simply continue executing the remaining commands in the script. set -o pipefail will cause a pipeline to fail if any of the commands in the pipeline failed. The default behavior is to only use the exit status of the last command.
Passing arguments to the bash script
#!/bin/bash # use predefined variables to access passed arguments #echo arguments to the shell echo $1 $2 $3 ' -> echo $1 $2 $3' # We can also store arguments from bash command line in special array args=("$@") #echo arguments to the shell echo ${args[0]} ${args[1]} ${args[2]} ' -> args=("$@"); echo ${args[0]} ${args[1]} ${args[2]}' #use $@ to print out all arguments at once echo $@ ' -> echo $@' # use $# variable to print out # number of arguments passed to the bash script echo Number of arguments passed: $# ' -> echo Number of arguments passed: $#'
Reading User Input
#!/bin/bash echo -e "Hi, please type the word: \c " read word echo "The word you entered is: $word" echo -e "Can you please enter two words? " read word1 word2 echo "Here is your input: \"$word1\" \"$word2\"" echo -e "How do you feel about bash scripting? " # read command now stores a reply into the default build-in variable $REPLY read echo "You said $REPLY, I'm glad to hear that! " echo -e "What are your favorite colours ? " # -a makes read command to read into an array read -a colours echo "My favorite colours are also ${colours[0]}, ${colours[1]} and ${colours[2]}:-)"
Declare simple bash array
#!/bin/bash #Declare array with 4 elements ARRAY=( 'Debian Linux' 'Redhat Linux' Ubuntu Linux ) # get number of elements in the array ELEMENTS=${#ARRAY[@]} # echo each element in array # for loop for (( i=0;i<$ELEMENTS;i++)); do echo ${ARRAY[${i}]} done
Read file into bash array
#!/bin/bash # Declare array declare -a ARRAY # Link filedescriptor 10 with stdin exec 10<&0 # stdin replaced with a file supplied as a first argument exec < $1 let count=0 while read LINE; do ARRAY[$count]=$LINE ((count++)) done echo Number of elements: ${#ARRAY[@]} # echo array's content echo ${ARRAY[@]} # restore stdin from filedescriptor 10 # and close filedescriptor 10 exec 0<&10 10<&-
Bash if / else / fi statements
1. Simple Bash if/else statement #!/bin/bash directory="./BashScripting" # bash check if directory exists if [ -d $directory ]; then echo "Directory exists" else echo "Directory does not exists" fi 2. Nested if/else #!/bin/bash # Declare variable choice and assign value 4 choice=4 # Print to stdout echo "1. Bash" echo "2. Scripting" echo "3. Tutorial" echo -n "Please choose a word [1,2 or 3]? " # Loop while the variable choice is equal 4 # bash while loop while [ $choice -eq 4 ]; do # read user input read choice # bash nested if/else if [ $choice -eq 1 ] ; then echo "You have chosen word: Bash" else if [ $choice -eq 2 ] ; then echo "You have chosen word: Scripting" else if [ $choice -eq 3 ] ; then echo "You have chosen word: Tutorial" else echo "Please make a choice between 1-3 !" echo "1. Bash" echo "2. Scripting" echo "3. Tutorial" echo -n "Please choose a word [1,2 or 3]? " choice=4 fi fi fi done
Bash Comparisons
1. Arithmetic Comparisons -lt < -gt > -le <= -ge >= -eq == -ne != #!/bin/bash # declare integers NUM1=2 NUM2=2 if [ $NUM1 -eq $NUM2 ]; then echo "Both Values are equal" else echo "Values are NOT equal" fi 2. String Comparisons = equal != not equal < less then > greater then -n s1 string s1 is not empty -z s1 string s1 is empty #!/bin/bash #Declare string S1 S1="Bash" #Declare string S2 S2="Scripting" if [ $S1 = $S2 ]; then echo "Both Strings are equal" else echo "Strings are NOT equal" fi
Bash File Testing
-b filename Block special file -c filename Special character file -d directoryname Check for directory existence -e filename Check for file existence -f filename Check for regular file existence not a directory -G filename Check if file exists and is owned by effective group ID. -g filename true if file exists and is set-group-id. -k filename Sticky bit -L filename Symbolic link -O filename True if file exists and is owned by the effective user id. -r filename Check if file is a readable -S filename Check if file is socket -s filename Check if file is nonzero size -u filename Check if file set-ser-id bit is set -w filename Check if file is writable -x filename Check if file is executable #!/bin/bash file="./file" if [ -e $file ]; then echo "File exists" else echo "File does not exists" fi #!/bin/bash while [ ! -e myfile ]; do # Sleep until file does exists/is created sleep 1 done
Bash for/while/until loop
#!/bin/bash # bash for loop for f in $( ls /var/ ); do echo $f done #!/bin/bash COUNT=6 # bash while loop while [ $COUNT -gt 0 ]; do echo Value of count is: $COUNT let COUNT=COUNT-1 done #!/bin/bash COUNT=0 # bash until loop until [ $COUNT -gt 5 ]; do echo Value of count is: $COUNT let COUNT=COUNT+1 done
Bash Functions
!/bin/bash # BASH FUNCTIONS CAN BE DECLARED IN ANY ORDER function function_B { echo Function B. } function function_A { echo $1 } function function_D { echo Function D. } function function_C { echo $1 } # FUNCTION CALLS # Pass parameter to function A function_A "Function A." function_B # Pass parameter to function C function_C "Function C." function_D
Bash Select
#!/bin/bash PS3='Choose one word: ' # bash select select word in "linux" "bash" "scripting" "tutorial" do echo "The word you have selected is: $word" # Break, otherwise endless loop break done exit 0
Case statement conditional
#!/bin/bash echo "What is your preferred programming / scripting language" echo "1) bash" echo "2) perl" echo "3) phyton" echo "4) c++" echo "5) I do not know !" read case; #simple case bash structure # note in this case $case is variable and does not have to # be named case this is just an example case $case in 1) echo "You selected bash";; 2) echo "You selected perl";; 3) echo "You selected phyton";; 4) echo "You selected c++";; 5) exit esac
Bash quotes and quotations
Quotations and quotes are important part of bash and bash scripting. Here are some bash quotes and quotations basics.
Escaping Meta characters
Before we start with quotes and quotations we should know something about escaping meta characters. Escaping will suppress a special meaning of meta characters and therefore meta characters will be read by bash literally. To do this we need to use backslash “\” character. Example:
#!/bin/bash #Declare bash string variable BASH_VAR="Bash Script" # echo variable BASH_VAR echo $BASH_VAR #when meta character such us "$" is escaped with "\" it will be read literally echo $BASH_VAR # backslash has also special meaning and it can be suppressed with yet another "\" echo "\"
Single quotes
Single quotes in bash will suppress special meaning of every meta characters. Therefore meta characters will be read literally. It is not possible to use another single quote within two single quotes not even if the single quote is escaped by backslash.
#!/bin/bash #Declare bash string variable BASH_VAR="Bash Script" # echo variable BASH_VAR echo $BASH_VAR # meta characters special meaning in bash is suppressed when using single quotes echo '$BASH_VAR "$BASH_VAR"'
Double Quotes
Double quotes in bash will suppress special meaning of every meta characters except “$”, “\” and “`”. Any other meta characters will be read literally. It is also possible to use single quote within double quotes. If we need to use double quotes within double quotes bash can read them literally when escaping them with “\”. Example:
#!/bin/bash #Declare bash string variable BASH_VAR="Bash Script" # echo variable BASH_VAR echo $BASH_VAR # meta characters and its special meaning in bash is # suppressed when using double quotes except "$", "\" and "`" echo "It's $BASH_VAR and \"$BASH_VAR\" using backticks: `date`"
Arithmetic Operations
echo '### Bash Arithmetic Expansion ###' # There are two formats for arithmetic expansion: $[ expression ] # and $(( expression #)) its your choice which you use echo 4 + 5 = $((4 + 5)) echo 7 - 7 = $[ 7 - 7 ] echo 4 x 6 = $((3 * 2)) echo 6 / 3 = $((6 / 3)) echo 8 % 7 = $((8 % 7)) echo 2 ^ 8 = $[ 2 ** 8 ] echo '### Declare ###' echo -e "Please enter two numbers \c" # read user input read num1 num2 declare -i result result=$num1+$num2 echo "Result is:$result " # bash convert binary number 10001 result=2#10001 echo $result # bash convert octal number 16 result=8#16 echo $result # bash convert hex number 0xE6A result=16#E6A echo $result Round floating point number: #!/bin/bash # get floating point number floating_point_number=3.3446 echo $floating_point_number # round floating point number with bash for bash_rounded_number in $(printf %.0f $floating_point_number); do echo "Rounded number with bash:" $bash_rounded_number done