Bash Scripting for Beginners Part II

S. Jackson
8 min readMay 25, 2021

This document will teach the reader more concepts of bash scripting, building on concepts learned in Part I.

Topics Covered:

  • Pass arguments to bash script
  • If statement (If, If then else, elif)
  • File test operators
  • Append output to end of text file
  • Logical AND operator
  • Logical OR operator

PASS ARGUMENT TO BASH SCRIPT

Arguments in bash are represented by numbers that are prefixed with a dollar sign, ie:

echo $1 $2 $3

In the example above, $1 represents the first argument, $2 represents the second argument, and $3 represents the third argument. This example simply tells the interpreter to print the arguments provided — but how do you input arguments? By including them when you call your shell file in the terminal

./helloWorld.sh Jan Justin Josh

The above tells the terminal to open the file like we learned in Part I, but it also provides the file with 3 string arguments of Jan, Justin, and Josh. When you press enter, the terminal will display all 3 arguments. The name of the shell script is also a variable itself, and to see it you must include $0

echo $0 $1 $2 $3

The terminal will print

./helloWorld.sh Jan Justin Josh

PASS ARGUMENT TO BASH SCRIPT AS ARRAY

Passing an argument to a bash script is the same as the above example, but in this case instead of the arguments being stored in a variable they will be stored in an array. To store user inputted arguments in an array you must do it like so:

args=( “$@” )

Note: ‘@’ is the variable the arguments are stored in

echo ${args[0]} ${args[1]} ${args[2]}

The above code first tells the interpreter that the user input must be stored in an array. The array is the args variable. Then the interpreter is instructed to print each value in the args array by index. The difference between this approach and the first is that in the first approach $0 represented the file name, but in this approach ${args[0]} represent the first value of the array.

To print all of the arguments at once, use the variable ‘$@’

echo $@

PRINT NUMBER OF ARGUMENTS BEING PASSED INTO A SCRIPT

There may be times where you will be unaware of how many arguments a user passes into a script, you can check this number by using the built in ‘#’ variable

echo $#

So, if you called the script in the terminal and provided 2 arguments, when you press enter the terminal will display 2 due to the line of code above

CONDITIONAL STATEMENTS IN BASH (Numbers)

‘If statements’ in bash scripting is somewhat the same as in any other language logically, the only difference being syntax. There are built in variables used as arithmetic operators in bash but you can also use standard operators as well. When using built in arithmetic operators, the condition must be wrapped in brackets. When using standard arithmetic operators, the condition must be wrapped in double parenthesis. Examples:

-lt means less than in bash scripting. To use this operator in bash you must use it like so:

value=5

if [ $value -lt 4 ]

In the above case, the condition is not true. Lets use the same example with a standard arithmetic operator that means the same thing

value=5

if (( $value < 4 ))

The condition is still not true, because 5 is not less than 4. Lets see an example using a standard arithmetic operator and evaluating two variables

value=5

value2=4

if (( $value < $value2 ))

Still, the condition is not true — but these are examples to show how different syntax is used depending on the operator used.

Now lets write a complete conditional statement using the built in arithmetic operator less than. We will make one complete statement if a condition isn’t true, and one for if it is.

value=5

value2=4

if [ $value -lt $value2 ]

then

echo ‘statement is true’

fi

The above code will not print anything because the statement is not true

value=5

value2=4

if [ $value2 -lt $value ]

then

echo ‘statement is true’

fi

The above code will print ‘statement is true’ because the variable value2 is less than the variable value.

CONDITIONAL STATEMENTS IN BASH (STRING)

Arithmetic operators can be used on strings as well.

= ←- equal to

== ←- equal to

!= ←- is not equal to

< ← — is less than, according to ASCII alphabetical order

> ←- is greater than, according to ASCII alphabetical order

-z ←- string is null, meaning it has zero length

firstName=john

if [ $firstName == john ]

then

echo condition is true

fi

In the above example, the terminal will display that the condition is true.

firstName=john

if [ $firstName == jon ]

then

echo condition is true

fi

In the above example, the terminal will not display anything because the condition is not true.

When using angle bracket arithmetic operators with strings, you must enclose the condition in double square brackets, for example:

This is wrong syntax

letter=a

if [ $letter < ‘b’ ]

This is right syntax

letter=a

if [[ $letter < b ]]

CONDITIONAL STATEMENTS IN BASH (IF…ELSE)

If else statements in bash scripting are used the same way you would use it in many other programming languages. Simply include else at the end to execute a statement if the conditions are not met

value=password

if [ $value == tables ]

then

echo ‘password is correct’

else

echo ‘password is incorrect’

fi

The above code will print ‘password is incorrect’ in the terminal

CONDITIONAL STATEMENTS (IF…ELIF…ELSE)

We’ve already talked about if and else, but in bash scripting theres another condition you can use called ‘elif’. Elif is much like else because it allows you to set a newer condition that can be evaluated. Lets say a user had to choose between two foods of either ‘pizza’ or ‘tacos’. Depending on the argument, a message will appear in the terminal.

echo ‘Between pizza and tacos, which is your favorite food?’

read favFood

food1=pizza

food2=tacos

if [ $food1 == $favFood ]

then

echo ‘The user chose pizza’

elif [ $food2 == $favFood ]

then

echo ‘The user chose tacos’

else

echo ‘The user chose neither tacos or pizza, but instead chose $favFood’

fi

Now, based off of everything we’ve learned so far this should be easy to follow. Notice that when using ‘elif’ you must also include then but with ‘else’ you do not. This is because else is not a conditional statement but more so telling the interpreter what to do if neither condition is met.

FILE TEST OPERATORS

Most of the time when working in the terminal you will be working with actual files, so its good to have some knowledge on file manipulation in the terminal.

In the next program, we will check to see if a file exist. First, we will prompt the user with a question

echo ‘Enter the name of file: \c’

The above line of code looks a little different than what we have been doing so far, but the only difference is it is telling the interpreter to let the user enter an input on the same line as the question and not under it. Lets continue.. starting from the top since we’ve explained that part:

echo ‘Enter the name of file: \c’

read file_name

if [ -e $file_name ]

then

echo ‘$file_name found’

else

echo ‘$file_name not found’

fi

Note: -e in the third line of code is a flag that basically checks if the, in this case $file_name, exist

Other options:

-f ← — checks if the file exist and if its a regular file

-d ←- checks if a directory exist

-b ←- checks if a block special file exist

-c ←- checks if a character special file exist

-s ←- checks whether file is empty or not

-r ←- checks whether file has read permission

-w ←- checks whether file has write permission

-x ←- checks whether file has execute permission

It’s important you understand the difference between block special files and character special files. Block special files are files like images, videos, audio, etc. Character special files are files of text.

APPEND OUTPUT TO END OF TEXT FILE

Next, you will learn how to append text to a text file.

In the program below, we will first ask the user for a file name. We will then check to see if the file exists and if its a regular file. If the file does exist, then we will see if we have permission to write to it, and if so write to it. If we do not have permission to write to it we will alert the user that we do not have write permission. If the file doesn’t exist at all we will alert the user that the file does not exist

echo ‘Enter file: \c’

read file_name

if [ -f $file_name ]

then

if [ -w $file_name ]

then

echo ‘Type your data. To quit, press ctrl + d’

cat >> $file_name

else

echo ‘File does not have write permissions’

fi

else

echo ‘$file_name does not exist’

fi

Note: cat is short for concatenate, ‘>>’ appends text to a file while ‘>’ overwrites the entire file with inputted text. Be sure to use the right operator

LOGICAL AND OPERATOR

The and operator allows you to check if two conditions are true. Lets say for example you’re a school that is offering a scholarship for young adults at least 15 but no older than 18 with at least a ‘B’ average in school. Lets say these were the only conditions to qualify, and the data was inputted by teachers. Lets begin our program:

Note: ‘&&’ is the and operator that makes sure two conditions are true

echo ‘Enter student age and cumulative grade: \c’

read age grade

if (( $age >= 16 )) && (( $age <= 18 ))

then

if [ $grade == B ]

then

echo ‘Student Qualifies’

elif [ $grade == A ]

then

echo ‘Student Qualifies’

else

echo ‘Student is within the age range, but must improve their grade’

fi

else

echo ‘Student does not meet the age requirement’

fi

Another way to write the same thing thats presented above is by using the -a flag instead of the ‘&&’. When using the -a flag, it isn’t necessary to have two conditions in separate brackets or double parenthesis — one will suffice. So lets look at it using the -a flag

echo -e ‘Enter student age and cumulative grade: \c’

read age grade

if [ “$age” -gt 15 -a “$age” -lt 19 ]

then

if [ $grade == B ]

then

echo ‘Student Qualifies’

elif [ $grade == A ]

then

echo ‘Student Qualifies’

else

echo ‘Student is within the age range, but must improve their grade’

fi

else

echo ‘Student does not meet the age requirement’

fi

LOGICAL OR OPERATOR

The OR operator is represented by double pipes || and is used the same way as the and ‘&&’ operator. The OR operator returns true if one of the conditions are true, whereas the and operator returns true if both conditions are true. Example of OR

userAge=25

userGender=male

if [ “$userAge” -gt 23 ] || [ “$userGender” == female ]

then

echo One or both of your conditions were met

else

echo No conditions were met

fi

The above example will result in true because although the user gender is not female, the user’s age is higher than 23 which makes at least one of the conditions true, thus triggering the result if the conditional statement is true. So, the program will execute and display ‘One or both of your conditions were met’

Another way to use the OR operator is by using the -o flag

userAge=25

userGender=male

if [ “$userAge” -gt 23 -o “$userGender” == female ]

then

echo One or both of your conditions were met

else

echo No conditions were met

fi

And the final way you can use the OR operator is by enclosing the condition in brackets and using the OR pipes in between the two conditions like so:

userAge=25

userGender=male

if [ “$userAge” > 23 || “$userGender” == female ]

then

echo One or both of your conditions were met

else

echo No conditions were met

fi

Note: Pay close attention to the different syntax used when using different OR operators.

This is the end of the Bash Scripting Tutorial Part II.

--

--

S. Jackson

Database Administrator | Web Developer | Software Developer