Bash Scripting Basics

Bash is the default shell for most GNU/Linux distributions and essential for automating tasks and system administration.

Basic script structure

#!/usr/bin/bash
echo "Hello World"

The shebang #!/usr/bin/bash tells the system which interpreter to use.

Variables

greeting=Hello
name=Sanatan
echo $greeting $name

No spaces around the = sign when assigning variables.

Arithmetic operations

sum=$((3+5))
echo $sum

Operators: + (addition), - (subtraction), * (multiplication), / (division), ** (exponential), % (modulo)

Calculator with decimals

echo "scale=2; 22/7" | bc

Use bc command for floating-point calculations. scale sets decimal places.

User input

read -p "Enter your first number: " x
read -p "Enter your second number: " y
sum=$((x+y))
echo "Sum: $sum"

Conditional statements

Comparison operators:

  • -eq : equal
  • -ne : not equal
  • -gt : greater than
  • -ge : greater than or equal
  • -lt : less than
  • -le : less than or equal
if [ 1 -lt 2 ]
then 
    echo "Condition is true"
fi
if [ 1 -eq 1 ]
then 
    echo "Equal"
elif [ 1 -gt 0 ] 
then
    echo "Greater"
else
    echo "Neither"
fi

Loops

for i in {1..10}
do
    echo $i
done
counter=1
while [ $counter -le 5 ]
do
    echo $counter
    ((counter++))
done

Functions

my_function() {
    echo "Hello, I'm a function"
    echo "Bye!"
}

# Call the function
my_function

File permissions

Make your script executable:

chmod +x script.sh
./script.sh

Bash scripting is fundamental for Linux automation and system management tasks.