422 likes | 522 Views
For a comprehensive knowledge and understanding of BASH shell scripting, this presentation aims to help beginners master shell scripting and gain hands-on CLI experience in no time. It is designed specifically for those who find it challenging to comprehend and read the manual thoroughly, which usually takes hours to read. <br><br>Created by Students of Amrita Vishwa Vidhyapeetham, Coimbatore:<br><br>Sai Mohnish M <br>Mohammed Aasil S<br><br>(2021-2025 Batch)
E N D
Introduction to BASH • Shell: It is simply an interface which executes commands. • BASH: BASH is the shell for the GNU OS. It stands for Bourne-Again-Shell. • The Unix Shell is both command interpreter and a programming language. • Shells can be used Interactively where it accepts arguments from the keyboard, otherwise Non-Interactively when it executes commands from a file. Such files are called as a Shell Script. • Shells have set of built-ins for ease-of execution of commands.
How to Start Scripting? • Open your UNIX terminal and type cd YourFilepath/and hit enter. • Type touch hello.sh and hit enter to create a shell script with a .sh extension. • You can also code in VS Code by typing code . & on your terminal.
BASH Commands • cd YourFilePath/ -- Changes the current working directory to ‘directory’. • cd .. – To change CWD to its immediate Parent directory. • ls – Displays the list of current folders. • pwd – Prints the name of the CWD. • mkdir – Creates a directory. • rmdir – Removes empty directories from directory lists. • touch – Create empty files. • cat – Displays files contents on Terminal.
More BASH Commands • clear – Removes the clutter of the CLI. • man – It is the manual page commands and it’s usage. • echo – Used to display text onto the output screen. • code . & – Opens VS Code and help run BASH without closing VS Code. • grep – Searches for a specified pattern specified using RegeX. • less – Displays file contents one page at a time, allowing scrolling. • chmod – Changes permissions of files, grant using +, revoke using –. • ps – Lists the running processes on the system, highly verbose. • Note: Using only double quotes (“ ”) in BASH is a good practice.
“Hello World!” (again) • Before we write our script, we need to specify what shell we are using. • We type cat /etc/shells command and we find out that our BASH is named /bin/bash. • Now we go back to our VS Code and code #! /bin/bash onto our hello.sh file. This specifies the script we are using. • Next line, type echo “Hello World!” and save the file. • Execute the script with the ./hello.sh command.
DENIED! • Let’s find out why our command was denied. We check File Permissions using the ls –al command. • We see our hello.sh file having only rw- meaning only read and write, but no execution permissions. • We type chmod +x hello.sh and hit enter. • Now when we execute our file with ./hello.sh command, we get our desired output.
Comments and Variables • Comments are done by typing # before any comment. • Variables are containers which stores data in them. • Variables are of 2 types in any UNIX based system, system and user variables. • System variables are created by UNIX itself and are defined in upper-case. • User variables are defined by the user and are usually in lower-case.
Let’s Script Variables! • echo $BASH, echo $BASH_VERSION, echo $HOME, echo $PWD are some system variables. • Type name=Lewis_Hamilton and in the next line, echo The Name is $name will yield The Name is Lewis_Hamilton in your terminal post execution. • Variable naming rules followed by C, C++, Python etc. are also followed by all Shells.
Let’s Read User Inputs! • Reading user inputs is done by the read command. • Try typing echo “Enter Name: “ read name echo “Entered Name: $name” one line after the other. • Try read name1 name2 name3 echo “Names: $name1, $name2, $name3” and enter space separated names in your terminal and observe the outputs.
Read Flags • read –p name specifies a prompt string to display. • read –sp name specifies a sensitive prompt string to display. • read –r name disables the behavior of treating backslashes as escape characters, i.e., treats backslashes as regular characters. • read –a name_array specifies a prompt array rather than a scalar. • read –n num name specifies a prompt string of up-to length num. • read –d ‘delim’ name1 name2 specifies prompts of 2 strings separated by a delimiter. • Note: You can combine flags together for extended functionality. Ex: -snp
Let’s Take Inputs! • Try read –p “username: “ name1 for regular prompt on the same line. • Although a good practice is to avoid prompts on the same line by doing echo “Enter Name” read name which is a valid identifier representation. • Try read –sp “username: “ name1 for a password prompt on the same line. • Try read –a arr echo “${arr[0]}, ${arr[1]}” will display first 2 elements of arr. • Try echo “Enter: “ read echo “$REPLY” will display the prompt without reading any var_name.
Passing Arguments • Try echo $1 $2 $3 and you can provide args when executing, i.e., ./file.sh a1 a2 a3 • Also try args=(“$@”) and in the next line, try echo ${args[2]} ${args[1]} ${args[0]} • Here, args is an array which stores all arguments a1 a2 a3 and displays them as a3 a2 a1 in this case. • Try echo $@ and itwill directly display all args in order. • Try echo $# and it will display the number of arguments used.
If and its Counterparts • Basic syntax of If Statement is : if [ condition ] then statement fi • Basic syntax of If - Else Statement is : if [ condition ] then statement else statement fi • Basic syntax of If - Elif Statement is : if [ condition ] then statement elif [ condition ] then statement else statement fi • Note: whenever using angled (<,=,>) comparator for strings, we use [[ condition ]]instead of [ condition ] to avoid errors. • We will learn about comparators in the next slide.
Comparators Integer Comparator String Comparator = - is equal to == - is equal to != - is not equal to < - is less than, in ASCII order > - is greater than, in ASCII order. -z - the string is NULL. • -eq = is equal to • -ne = is not equal to • -gt = is greater than • -ge = is greater than or equal to • -lt = is less than • -le = is less than or equal to • < - is less than • <= - is less than or equal to
Echo Flags • -n => does not allow the display of trailing newline character. • -e => interprets backslash sequences. • -E => does not interpret backslash sequences. • -z => checks if variable length is zero and returns True if zero.
File Flags • [ -e $file1 ] => returns True if file exists, else False. • [ -f $file1 ] => returns True if file is regular, else False, even if a device file. • [ -d $dir1 ] => returns True if directory exists, else False. • [ -b $file1 ] => returns True if it is a block (.img,.mpeg) file, else False. • [ -c $file1 ] => returns True if it is a character file, else False. • [ -s $file1 ] => returns True if it is a file is NOTempty, else False. • [ -r/w/x $file1 ] => returns True if it is a file is NOTempty, else False. • Note: The spacing between [ and flag is necessary to avoid errors.
Let’s Write Onto a File! • Firstly, we need to take user input on what file to be written onto. • Next, we need to check if the file exists in the first place, else, not exists prompt and fi. • Next, If file exists, we check if we have write permission for the file, else, fi. • Next, If have the write permission, we write onto our file using the cat command. • We use cat > file1 for appending data, we quit from cat using Ctrl + D.
Logical Operators • Logical AND : -a is the flag used for this operation. && is also valid. • Look at the image and recall the integer comparators used in the program. • Logical OR : -o is the flag used for this operation. || is also valid. (piping operator) • When using flags for logical operations, 1 pair of [] is sufficient, otherwise we use 2 pairs. e.g. [“$v” –gt 18] && [“$v” –lt 30]. • Logical NOT : ! is the flag used for this operation.
Arithmetic Operations • Take num1=44 and num2=33, we do addition using this command: echo $(( num1 + num2 )). Note: Space is required between (( and Operand. • We can perform +, -, *, /, % operations using the above command. • Alternatively, we can perform Arithmetic operations using the expr command. echo $(expr $num1 + $num2 ). • It is important to note that this command works well except for multiplication (*) as * is not escaped under expr command. We instead use ( \* ) for multiplication.
Floating Point Arithmetic • We can’t use the previous methods for floating point numbers as it only accepts integer arguments. • So we use bc which is a precision calculator language and is used as follows: echo “44.0 + 11.1” | bc. We have piped first command into bc for execution. • This command works well for all operations, however when performing ( / ) division, default precision scale is set as 0 decimal places. It is written as: echo “scale=2;44.0/11.1” | bc. • For executing math operations, we write echo “scale=2;sqrt($num)” | bc –l • Check out man bc command for the manual of this calculator.
BASH RegeX • “ * ” – Matches 0 or more characters. • “ ? “ – Checks for special characters. • “ [a-z] ” – Checks if character entered is between a to z. • “ [0-9] “ – Checks if character entered is between 0 to 9.
The Case Statement • Let’s try case statements with arguments. • Basic syntax of case statement is as follows: case $vehicle in “case1” ) echo statement ;; “case2”) echo statement ;; * ) echo “default_case_output” ;; esac • Maintain a space after every case and ). • Take a look at the program in this slide and try executing it.
Arrays • Arrays in BASH are initialized as : arr=(“data0” “data1” “data2”). • All elements of the arrayare printed using echo “${arr[@]}”. • The index locations of all elements of array are printed using “${!arr[@]}”. • The size of the array is printed using “${#arr[@]}”. • unset arr[index] removes the element and replaces it with garbage value. • BASH permits array assignments at any location. e.g., arr[6]=“data6”. • BASH also permits usage of strings using arrays, however the whole string is stored in the zeroth index of the array.
Arrays (Contd.) • Arrays are passed using func_name arr1[@] command. • Arrays are read from user using: read –ra array command. • The same Array is addressed within the function using (“${!1}”).
Strings in BASH • String size is ${#str}. • Indexing a string is done using ${str:$iterator:1}.
WHILE loop • The while loop loops through a block of code as long as a specified condition is True. • Syntax : • Example : • To print from 1 to 10. (OR)
Sleep 💤 • Sleep command can make the program wait for a given time in seconds. • The following program will wait for 1 second after incrementing n.
Reading file content • IFS • IFS is a special variable used to specify the delimiter character used to separate fields (or words) in a string. • By default, the IFS variable is set to a space, a tab, and a newline character. • -r: reads backslash(/) as a literal character and not special. • Filename to be read to is given at last. (readfile.sh in the above case)
UNTIL loop • The Until loop is used to iterate over a block of commands until the required condition is false. • Syntax: • Example: • To print from 1 to 10.
FOR loop • Syntax: • There are multiple ways of using for loops in bash • Usual way (like in C++, C) • Example: • To print from 0 to 4.
Syntax: • Output: • Example:
Syntax: • Output: • Example:
Syntax: • Output: • Example:
Select loop • The select loop provides an easy way to create a numbered menu from which users can select options. • Syntax: • Example: • Output:
Break & Continue • Break statement is used to terminate the loop immediately. • Continue statement, on the other hand, is used to skip a particular iteration of the loop. • Example: • Output: • Note that iteration when, i = 2 is skipped. • Loop terminates after i > 5.
Functions • result=${func_name $func_arg} • Syntax: • With Arguments: • Here the $i corresponds to ith argument passed.
Local keyword • In the above program, you can notice the output before and after function is giving a different name. • This is due to the variable inside the function changing the global variable `name`. • This can be prevented by adding the `local` keyword in the function.
Checking for a file using functions • In the given program, we have two functions: • usage() – we use this when there are no arguments • is_file_exist() – the first argument is the filename store in var `file` • -f checks for the file in the pwd (present working directory) • Returns 1 if yes, else returns 0 • If the function returns 1 • Prints (“file found”) Note: `$#` counts the number of arguments passed
Read-only Variables • When a variable is declared readonly, it’s value cannot be changed again. • It is also applicable to functions.
Signals and Traps • The POSIX signal implementation ensures that if a process is already handling a signal, other incoming signals are suspended until the handler returns.
S&T Continued • Based on the signal returned we can set a trap action. • Example: • The following program prints until 10 with a delay of 10 sec per iteration. • The trap statement will execute when `SIGINT` is detected. • SIGINT is an interrupt from the keyboard. • From the output, it can be understood that even those there is an interrupt from keyboard (SIGINT), the program still executes with the prompt.