Windows & Linux · Basic Bash Shell Scripting

Basic Bash Shell Scripting

Turn repetitive terminal tasks into small, reusable programs. Learn the shebang, variables, conditionals, loops, and functions—then apply them with real examples.

What is Bash Shell Scripting?

Bash (Bourne Again Shell) is both a command language and a shell for Unix-like systems. Bash scripting means writing a sequence of commands into a file so they can run together—automating file work, user input, loops, and system admin tasks.

Bash scripting turns repeatable steps into clean, versionable scripts that manage systems and solve problems using built-in Unix tools.

Why and When is Bash Scripting Beneficial?

Bash Scripting Fundamentals

Shebang & Execution

#!/bin/bash
# file: script.sh

echo "Hello from Bash"

The first line #!/bin/bash (the shebang) tells the OS to run the file with Bash. Make it executable and run it:

chmod +x script.sh
./script.sh

Variables & Read

name="Mark"
echo "Hi, $name!"

read -p "Your favorite distro? " distro
echo "Nice choice: $distro"

Conditionals

read -p "Enter a number: " n
if [ "$n" -gt 10 ]; then
  echo "Greater than 10"
elif [ "$n" -eq 10 ]; then
  echo "Exactly 10"
else
  echo "Less than 10"
fi

Loops

For — when you know the iteration set; While — continue while condition is true.

# for over values
for i in 1 2 3; do
  echo "Number $i"
done

# for over files in a folder
for f in *.log; do
  echo "Found: $f"
done

# while loop
count=0
while [ $count -lt 3 ]; do
  echo "Count: $count"
  count=$((count+1))
done

Functions

greet(){
  echo "Hello, $1!"
}

greet "Mark"

Functions help you organize code, avoid repetition, and reuse logic across scripts.

Script Structure Tips

#!/bin/bash
set -euo pipefail

log(){ printf "[%s] %s\n" "$(date +%T)" "$*"; }
main(){
  log "Starting"
  # work goes here
  log "Done"
}
main "$@"

Script Examples

1) Hello World

2) User Input

3) File Existence Check

4) For Loop

5) Simple Backup Script

6) Function Example

Conclusion

We covered the essentials of Bash scripting—shebang, variables, input, conditionals, loops, and functions—then applied them in practical examples. Keep experimenting and check man bash for deeper options.

Back to Home