Bash Scripting Quickstart Guide
This guide provides a comprehensive introduction to Bash scripting, covering basic syntax, variables, conditional statements, loops, file operations, and functions. It includes examples, key commands, and explanations to help automate tasks in Linux environments efficiently.
Bash scripting
Bash script is used to make linux utilities and in makefile to automate your task.
Without wasting anymore time let’s begin the bash quickstart.
💡Note: First line of every script file contains #!/bin/bash which tells os to use bash | zsh | fish shell. (It is not require though but it is generally good practice to include it)
Creating a bash script file
touch <filename>.sh→ Used to create bash file.chmod +x <filename>.sh→ Make it executable (by default it is only in read and write mode./<filename>.sh→ used to execute the file and it shows output in terminal
comments
# single line comment
# multi line comment starts with << followed by any word that is used to close multi line comment
<<comment-start
your comment
comment-start
variables
# declaring variable
VAR_NAME="some_value" # white space are not allowed after and before '='
# storing command output
LIST_DIR=$(ls -la) # we can execute any command between '$()'
# accessing variable
echo $LIST_DIR
echo $VAR_NAME
Constant
# declaring constants
readonly PI=3.14
readonly PIE=3.14 # readonly variable
echo "The value of PIE is $PIE"
PIE=20 # Throws an error
Taking Input from User
We use read keyword for reading input from user
# directly asking for input
read NAME
echo "Entered name is $NAME"
# asking with prompt string
read -p "Enter your age " AGE
echo "Entered age is $AGE"
Conditional statement
Conditional statement in bash scripting is little bit weird compared to other languages
If-else statement
# if if [ condition ]; then # code fi # if else if [ condition ]; then # code else # else code fiif-else ladder
if [ condition1 ]; then # commands to execute if condition1 is true elif [ condition2 ]; then # commands to execute if condition2 is true else # commands to execute if all conditions are false fi
Example
# if else
NAME="arshil"
if [ "$NAME" = "arshil" ]; then
echo "Name is arshil"
else
echo "Name is not arshil"
fi
# if elif else
read -p "Enter your age: " AGE
if [ $AGE -lt 18 ]; then
echo "There is a long way to go :)"
elif [ $AGE -ge 18 ] && [ $AGE -le 60 ]; then
echo "Enjoy your life :)"
else
echo "Life is about to end :("
fi
Different types of comparison operator
Numeric comparison operator:
| Operator | Description | Example |
|---|---|---|
-eq | Equal to | [ $a -eq $b ] |
-ne | Not equal to | [ $a -ne $b ] |
-lt | Less than | [ $a -lt $b ] |
-le | Less than or equal to | [ $a -le $b ] |
-gt | Greater than | [ $a -gt $b ] |
-ge | Greater than or equal to | [ $a -ge $b ] |
String comparison operator:
| Operator | Description | Example |
|---|---|---|
= | Equal to | [ "$a" = "$b" ] |
!= | Not equal to | [ "$a" != "$b" ] |
< | Less than, in ASCII alphabetical order | [ "$a" < "$b" ] |
> | Greater than, in ASCII alphabetical order | [ "$a" > "$b" ] |
-z | True if the string is empty | [ -z "$a" ] |
-n | True if the string is not empty | [ -n "$a" ] |
File comparison operator:
| Operator | Description | Example |
|---|---|---|
-e | True if the file exists | [ -e file.txt ] |
-f | True if the file is a regular file (not a directory) | [ -f file.txt ] |
-d | True if the file is a directory | [ -d /path/to/dir ] |
-r | True if the file is readable | [ -r file.txt ] |
-w | True if the file is writable | [ -w file.txt ] |
-x | True if the file is executable | [ -x script.sh ] |
-s | True if the file has a size greater than zero | [ -s file.txt ] |
-nt | True if file1 is newer than file2 | [ file1 -nt file2 ] |
-ot | True if file1 is older than file2 | [ file1 -ot file2 ] |
File operations
if [ -f "script.sh" ] && [ -r "script.sh" ] && [ -w "script.sh" ] && [ -x "script.sh" ]; then
echo "script.sh exists and it is readable, writable and executable"
else
echo "script.sh does not exists"
fi
Switch case
Though we don’t use it often, it can sometimes be very handy
echo "Enter your choice"
echo "n = neofetch"
echo "g = gdu"
read choice
case $choice in
n) neofetch;;
g) gdu;;
*) echo "Invalid choice"
esac
Loops
It’s syntax looks similar to rust like loops
for i in {start..end}
do
# code to perform
done
Example
for i in {1..5}
do
echo "Number is $i"
done
for i in Arshil Hapani
do
echo "Word is $i"
done
# we can also use for i in 1 3 3 5 6...
Reading file using for loop
for ch in $(cat hello.txt)
do
echo $ch
done
While loop
while [ condition ]
do
# code
done
Example
I=1
while [ $I -le 5 ]
do
echo "Number is $I"
let I++
done
Until loop
I don’t think there is need of such loop. It is similar to while until it executes while it’s condition is false. Sounds confusing, right? It checks for false condition while while loop checks for true condition to execute current iteration.
I=1
until [ $I -gt 5 ]
do
echo "Number is $I"
let I++
done
Break and continue
for i in {1..10}
do
if [ $i -eq 4 ]; then
continue
elif [ $i -eq 7 ]; then
break
fi
echo "Number is $i"
done
Expressions
In bash we cannot use expressions directly like we do in other languages. We need to use let keyword followed by expression
let <expression>
Example
I=10
J=20
let J-=I+90
echo $J
let I+=J*10
echo $I
Can you guess the output?
Accessing script name
echo "Script name is $0"
Functions
Creating simple function
function name {
echo "Called name"
}
# or
name1() {
echo "called name1"
}
# calling function
name
name1
Passing arguments
function myFn {
NAME=$1 # arg1
SURNAME=$2 # arg2
echo "Hello Mr. $NAME $SURNAME"
}
# passing argument
myFn Arshil Hapani # direct args passing
Passing argument while running (program parameters)
| Symbol | Description |
|---|---|
$# | Displays number of arguments |
$@ | Displays all arguments |
$1 $2… | To use the argument |
echo "Number of arguments $#"
echo "Args = $@"
echo "First args: $1"
echo "Second args: $2"
Bash variable
Some of the global bash variable which we can use to make our life easier.
H
Here is the comprehensive table describing essential bash variable:
| Variable | Description | Example Usage |
|---|---|---|
$0 | The name of the script currently being executed. | echo $0 |
$1, $2, ... | The first, second, and subsequent positional parameters (arguments to the script). | echo $1 |
$# | The number of positional parameters passed to the script or function. | echo $# |
$@ | All positional parameters as separate quoted strings. | echo $@ |
$* | All positional parameters as a single string. | echo $* |
$? | The exit status of the last command executed (0 for success, non-zero for failure). | echo $? |
$$ | The process ID (PID) of the current shell or script. | echo $$ |
$! | The PID of the last background process. | some_command & echo $! |
$USER | The current logged-in user’s username. | echo $USER |
$HOME | The home directory of the current user. | echo $HOME |
$PATH | A colon-separated list of directories where executable files are searched. | echo $PATH |
$PWD | The current working directory. | echo $PWD |
$OLDPWD | The previous working directory. | echo $OLDPWD |
$IFS | Internal Field Separator used by the shell to determine word boundaries. | echo $IFS |
$RANDOM | Generates a random integer between 0 and 32767. | echo $RANDOM |
$SECONDS | The number of seconds the script has been running. | echo $SECONDS |
$LINENO | The current line number in the script. | echo $LINENO |
Some useful keywords
sleep→ Used to make script sleepexit→ To terminate the scriptlogger→ used to write logs in/var/messagesfile
