DEV Community

Cover image for Bash Scripting: The Complete Guide (From Zero to Advanced)
Farhad Rahimi Klie
Farhad Rahimi Klie

Posted on • Edited on

Bash Scripting: The Complete Guide (From Zero to Advanced)

Bash (Bourne Again SHell) is one of the most important tools every developer, DevOps engineer, system administrator, and backend engineer must master. Bash is not just a command-line interface—it is a powerful scripting language used to automate systems, deploy applications, manage servers, and glue entire infrastructures together.

This article is a complete Bash scripting reference, covering everything from fundamentals to advanced scripting techniques.


1. What Is Bash?

Bash is:

  • A shell (command interpreter)
  • A scripting language
  • The default shell on most Linux systems
  • Available on macOS and Windows (WSL, Git Bash)

Bash executes commands entered by the user or stored inside scripts.


2. Bash vs Shell

  • Shell is a general term for command interpreters (sh, zsh, fish)
  • Bash is an enhanced version of the original Bourne Shell (sh)
  • Bash adds:

    • Arrays
    • Command history
    • Job control
    • Advanced string manipulation

3. Bash Script File Basics

A Bash script is a text file containing Bash commands.

File extension

script.sh
Enter fullscreen mode Exit fullscreen mode

Shebang (Mandatory)

#!/bin/bash
Enter fullscreen mode Exit fullscreen mode

This tells the OS which interpreter to use.


4. Making a Script Executable

chmod +x script.sh
Enter fullscreen mode Exit fullscreen mode

Run it:

./script.sh
Enter fullscreen mode Exit fullscreen mode

5. Comments in Bash

# This is a comment
Enter fullscreen mode Exit fullscreen mode

No multi-line comment syntax exists natively.


6. Variables in Bash

Variable Declaration

name="Farhad"
age=25
Enter fullscreen mode Exit fullscreen mode

❗ No spaces around =.

Accessing Variables

echo $name
echo ${age}
Enter fullscreen mode Exit fullscreen mode

7. Environment Variables

export PATH=$PATH:/custom/path
Enter fullscreen mode Exit fullscreen mode

View:

printenv
Enter fullscreen mode Exit fullscreen mode

8. Read User Input

read username
echo "Hello $username"
Enter fullscreen mode Exit fullscreen mode

With prompt:

read -p "Enter name: " name
Enter fullscreen mode Exit fullscreen mode

9. Positional Parameters

./script.sh arg1 arg2
Enter fullscreen mode Exit fullscreen mode

Inside script:

$0  # script name
$1  # first argument
$2  # second argument
$@  # all arguments
$#  # number of arguments
Enter fullscreen mode Exit fullscreen mode

10. Exit Codes

Every command returns a status code:

  • 0 → success
  • Non-zero → failure
echo $?
Enter fullscreen mode Exit fullscreen mode

Exit manually:

exit 1
Enter fullscreen mode Exit fullscreen mode

11. Conditional Statements

if

if [ $age -gt 18 ]; then
  echo "Adult"
fi
Enter fullscreen mode Exit fullscreen mode

if-else

if [ "$name" == "Ali" ]; then
  echo "Hello Ali"
else
  echo "Unknown user"
fi
Enter fullscreen mode Exit fullscreen mode

elif

if [ $age -lt 18 ]; then
  echo "Minor"
elif [ $age -lt 60 ]; then
  echo "Adult"
else
  echo "Senior"
fi
Enter fullscreen mode Exit fullscreen mode

12. Comparison Operators

Numeric

  • -eq equal
  • -ne not equal
  • -gt greater than
  • -lt less than
  • -ge greater or equal
  • -le less or equal

String

  • = equal
  • != not equal
  • -z empty
  • -n not empty

13. Logical Operators

[ condition1 ] && [ condition2 ]
[ condition1 ] || [ condition2 ]
! condition
Enter fullscreen mode Exit fullscreen mode

14. Case Statement

case $option in
  start)
    echo "Starting"
    ;;
  stop)
    echo "Stopping"
    ;;
  *)
    echo "Invalid option"
    ;;
esac
Enter fullscreen mode Exit fullscreen mode

15. Loops

for loop

for i in 1 2 3; do
  echo $i
done
Enter fullscreen mode Exit fullscreen mode

Range:

for i in {1..5}; do
  echo $i
done
Enter fullscreen mode Exit fullscreen mode

while loop

while [ $count -lt 5 ]; do
  echo $count
  ((count++))
done
Enter fullscreen mode Exit fullscreen mode

until loop

until [ $count -gt 5 ]; do
  echo $count
  ((count++))
done
Enter fullscreen mode Exit fullscreen mode

16. break and continue

break
continue
Enter fullscreen mode Exit fullscreen mode

17. Functions

my_function() {
  echo "Hello"
}
Enter fullscreen mode Exit fullscreen mode

Call:

my_function
Enter fullscreen mode Exit fullscreen mode

With arguments:

greet() {
  echo "Hello $1"
}
greet Farhad
Enter fullscreen mode Exit fullscreen mode

18. Return Values from Functions

return 0
Enter fullscreen mode Exit fullscreen mode

Retrieve:

$?
Enter fullscreen mode Exit fullscreen mode

19. Arrays

arr=(apple banana orange)
Enter fullscreen mode Exit fullscreen mode

Access:

echo ${arr[0]}
Enter fullscreen mode Exit fullscreen mode

All elements:

echo ${arr[@]}
Enter fullscreen mode Exit fullscreen mode

Length:

echo ${#arr[@]}
Enter fullscreen mode Exit fullscreen mode

20. Associative Arrays

declare -A user
user[name]="Farhad"
user[age]=25
Enter fullscreen mode Exit fullscreen mode

21. String Manipulation

str="Hello World"
Enter fullscreen mode Exit fullscreen mode

Length:

${#str}
Enter fullscreen mode Exit fullscreen mode

Substring:

${str:0:5}
Enter fullscreen mode Exit fullscreen mode

Replace:

${str/World/Bash}
Enter fullscreen mode Exit fullscreen mode

22. Arithmetic Operations

((a=5+3))
echo $a
Enter fullscreen mode Exit fullscreen mode

Or:

expr 5 + 3
Enter fullscreen mode Exit fullscreen mode

23. Command Substitution

date=$(date)
Enter fullscreen mode Exit fullscreen mode

Or:

date=`date`
Enter fullscreen mode Exit fullscreen mode

24. Input / Output Redirection

Redirect output

ls > file.txt
Enter fullscreen mode Exit fullscreen mode

Append:

ls >> file.txt
Enter fullscreen mode Exit fullscreen mode

Redirect input

wc -l < file.txt
Enter fullscreen mode Exit fullscreen mode

25. Pipes

ps aux | grep root
Enter fullscreen mode Exit fullscreen mode

26. File Test Operators

-f file    # regular file
-d dir     # directory
-e file    # exists
-r file    # readable
-w file    # writable
-x file    # executable
Enter fullscreen mode Exit fullscreen mode

27. Signals and Traps

trap "echo Interrupted" SIGINT
Enter fullscreen mode Exit fullscreen mode

28. Debugging Bash Scripts

Run with debug mode:

bash -x script.sh
Enter fullscreen mode Exit fullscreen mode

Enable inside script:

set -x
Enter fullscreen mode Exit fullscreen mode

Stop:

set +x
Enter fullscreen mode Exit fullscreen mode

29. Error Handling

set -e
Enter fullscreen mode Exit fullscreen mode

Exit on error.

Custom handling:

command || echo "Failed"
Enter fullscreen mode Exit fullscreen mode

30. Process Management

Background:

command &
Enter fullscreen mode Exit fullscreen mode

Wait:

wait
Enter fullscreen mode Exit fullscreen mode

PID:

$$
Enter fullscreen mode Exit fullscreen mode

31. Cron Jobs (Automation)

Edit cron:

crontab -e
Enter fullscreen mode Exit fullscreen mode

Example:

0 2 * * * /path/script.sh
Enter fullscreen mode Exit fullscreen mode

32. Best Practices

  • Always use #!/bin/bash
  • Quote variables "${var}"
  • Use set -euo pipefail
  • Use functions
  • Avoid hard-coded paths
  • Log outputs

33. Real-World Use Cases

  • Deployment scripts
  • Server monitoring
  • Log rotation
  • CI/CD pipelines
  • Backup automation
  • DevOps orchestration

34. Final Thoughts

Bash scripting is not optional for serious developers and engineers. It is the backbone of Linux systems, cloud infrastructure, and DevOps workflows. Mastering Bash gives you control over the operating system itself.

If you understand Bash deeply, you control the machine—not the other way around.

Top comments (2)

Collapse
 
a-k-0047 profile image
ak0047

Thank you for sharing this article!
As a beginner with Bash scripting, I found it really helpful and practical.

Collapse
 
farhadrahimiklie profile image
Farhad Rahimi Klie

have a good job my friend