Development & Shell Scripting

By admin, 13 April, 2025

๐Ÿš Shell Scripting One-Page Manual (Bash)

๐Ÿ“Œ Basics

Shebang (First Line)

#!/bin/bash

Tells the system to use Bash to run the script.

Run a Script

chmod +x script.sh     # Make executable
./script.sh            # Run

๐Ÿ”ง Variables

NAME="Alice"
echo "Hello, $NAME"
  • No space around =
  • Use $VAR to access

๐Ÿงฎ Conditionals

if [ "$AGE" -ge 18 ]; then
    echo "Adult"
else
    echo "Minor"
fi

Comparison operators:

  • Strings: =, !=, -z, -n
  • Numbers: -eq, -ne, -lt, -le, -gt, -ge

๐Ÿ” Loops

For Loop

for i in 1 2 3; do
    echo $i
done

While Loop

while [ "$x" -le 5 ]; do
    echo $x
    ((x++))
done

๐Ÿ“ฆ Functions

greet() {
    echo "Hello, $1"
}
greet "Bob"
  • $1, $2, etc. are arguments
  • return optional; use echo for output

๐Ÿ“ File Tests

if [ -f file.txt ]; then
    echo "It's a file"
fi
  • -f: regular file
  • -d: directory
  • -e: exists
  • -r, -w, -x: read/write/execute

๐Ÿ“š Useful Built-ins

Command Purpose
read VAR Read input
echo Print text
cd, pwd Change/print directory
exit Exit script
source file Run a script in current shell

๐Ÿ“‘ Tips

  • Use set -e to exit on error
  • Use #!/bin/bash -x for debugging
  • Quote variables: "$VAR" to avoid word splitting
  • Always check $? for last command status

๐Ÿš Bash Shell Scripting Cheat Sheet


๐Ÿ”น BASICS

#!/bin/bash         # Shebang
chmod +x script.sh  # Make script executable
./script.sh         # Run script

๐Ÿ”น VARIABLES

NAME="Alice"
echo "Hello, $NAME"
  • No spaces around =
  • Use "$VAR" to prevent word splitting

๐Ÿ”น CONDITIONALS

if [ "$A" -gt 10 ]; then
  echo "Greater"
elif [ "$A" -eq 10 ]; then
  echo "Equal"
else
  echo "Less"
fi

Operators:

Type Operators
Strings =, !=, -z, -n
Numbers -eq, -ne, -lt, -le, -gt, -ge
Files -f, -d, -e, -r, -w, -x

๐Ÿ”น LOOPS

# For Loop
for i in 1 2 3; do echo $i; done

# While Loop
while [ $x -le 5 ]; do echo $x; ((x++)); done

๐Ÿ”น FUNCTIONS

myfunc() {
  echo "Arg1 is $1"
}
myfunc "Hello"

๐Ÿ”น INPUT & OUTPUT

read -p "Enter name: " NAME
echo "You typed: $NAME"

๐Ÿ”น SPECIAL VARIABLES

Symbol Description
$0 Script name
$1..$9 Arguments
$# Number of arguments
$@ All arguments
$? Exit status of last command
$$ PID of script

๐Ÿ”น FILE TESTS

[ -f file.txt ] && echo "Regular file"
[ -d dir ] && echo "Directory"
[ -e path ] && echo "Exists"

๐Ÿ”น DEBUGGING & SAFETY

set -e    # Exit on error
set -u    # Error on undefined variables
set -x    # Debug mode (prints commands)