Skip to content

Bash Scripting

Notes

  • A shell is a program that takes commands from the keyboard (or a file) and gives them to the operating system to perform.
  • Bash is a command language interpreter; I think of it as a programming language that has a special syntax for executing commands.
  • Scripting is the process of writing a series of commands to a file and sending them to a shell to execute.
  • I created a file called ja8.sh to test the script:
    • It failed with permission or command not found error.
    • I had to change the file permissions to make it executable.
    • I solved the permission issue by running in sudo mode.
    • I made the file executable by running chmod +x ja8.sh.

ja8.sh

  • To know the current shell in place run: echo $SHELL # /bin/bash | /bin/zsh
  • It is a good practice to add a shebang line to the top of the script to tell the shell which interpreter to use (Shebang, 2023).
  • Shebang or hash-bang is the symbol #! at the beginning of a script. It is used to tell the shell which interpreter to use to execute the script.
  • The shebang must be followed by the path to the interpreter. For example, to use the Bash interpreter, the shebang line would be: #!/bin/bash
  • Another way to run a script is to use the bash command: bash ja8.sh
  • while scripting, executing commands within $(command) will return the output of the command, which can be assigned to a variable. like user=$(whoami) or n=$(ls -l | wc -l).
  • We call this command substitution.
  • To use a variable within a string, we use the $ sign. For example, echo "$greeting $user! Today is $day, which is a great day!".
  • Some special variables are set by the shell and available by default. For example, $BASH_VERSION is the version of the Bash shell.
  • Parameter expansion - is the process of modifying a variable’s value. For example, ${parameter:-word} - If $parameter is unset or null, the expansion of word is substituted. Otherwise, the value of the $parameter is substituted.
  • Descriptors:
    • > - Redirects output to a stdout, which is the default output of a command. It can be a file or a terminal.
    • 2> - Redirects output to a stderr, which is the error output of a command. It can be a file or a terminal.
    • <- Redirects input to a stdin. It can be a file or a terminal input.
  • echo $? - returns the exit status of the last command. 0 means success, and 1 means failure.
  • exit - terminates the script.
  • Conditionals: if, elif, else, fi, then. Where fi is the end of the conditional block.
  • Positional parameters:
    • Used to access the arguments passed to the script.
    • Use $1, $2, $3, etc. to access the arguments.
    • $# - returns the number of arguments passed to the script.
    • $* - returns all the arguments passed to the script.

Useful Bash Commands

  • which $arg - displays the full path of the executable of the $arg.
  • chmod +x $arg - makes the file $arg executable.
  • file $filePath - displays the type of the file.
  • man $command - displays the manual page of the $command.
  • tar -czf $archiveName $files - creates a compressed archive of the $files. c creates the archive, z compresses the archive, and f specifies the name of the archive.
  • whoami - displays the current user.
  • find $path ...$options - searches for files in a directory hierarchy. For example, find . -name "*.txt" will search for all files with the .txt extension in the current directory. or find -type f will search for all files in the current directory.
  • wc -l - counts the number of lines in the input.
  • -d $folderName - checks if the $folderName exists.

SH examples

Backup a folder

#!/bin/bash
tar -czf ./images.tar.gz ./images

Variables

#!/bin/bash

greeting="Hello"
user=$(whoami)
day=$(date +%A)

echo "$greeting $user! Today is $day, which is a great day!"
echo "Your Bash shell version is: $BASH_VERSION. Enjoy!"

variables

Functions

#!/bin/bash

function user_details { # function definition
    echo "Hello World"
    echo "User Name: $(whoami)"
    echo "Home Dir: $HOME"
}

hello # call the function

functions

Conditionals

#!/bin/bash
condition = true
another_condition = false

if $condition; then
    # do something
    echo "condition if then"
elif $another_condition; then
    # do something
    echo "condition elif then"
else
    # do something
    echo "condition else"
fi

Comparisons

#!/bin/bash

## numeric comparison: -eq, -ne, -gt, -ge, -lt, -le
### -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

num1=20
num2=5

if [ $num1 -gt $num2 ]; then
    echo "$num1 is greater than $num2"
fi

## string comparison: =, ==, !=, <, >, -z, -n
### -z checks if the string is empty
### -n checks if the string is not empty
### = and == are the same
### != is not equal
### < and > are used for alphabetical order

str1="hello"
str2="world"

if [ $str1 = $str2 ]; then
    echo "$str1 is equal to $str2"
fi

Loops

#!/bin/bash

## for loop
for i in 1 2 3 4 5;
do
    echo $i
done

## while loop
counter=0

while [ $counter -lt 10 ];
do
    echo $counter
    ((counter++))
done

## until loop

counter=20

until [ $counter -lt 10 ];
do
    echo $counter
    ((counter--))
done

## Example

for i in $(cat ./names.txt); do echo -n $i | wc -c; done # prints the length of each name in the names.txt file

Solution

  • I actually finished the tutorial til the end; it was a good one. I learned a lot of new things, and I’m glad I did it.
  • I did not use their example entirely for two reasons:
    • The example interacts with home directories, and I don’t want to mess with my home directory. So I changed the code to use the path that is provided to the script.
    • There was a syntax error in the example, and I fixed it. when they tried to sum the number of files and directories using the let command.
  • Here is the output with the syntax error:

syntax error

  • Here is the output with the fixed code:

fixed code

  • Here is the result where the zip file is created:

zip file

References