Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Shell Scripting

Hash shell supports POSIX-compatible shell scripting for automation and reusable scripts.

Running Scripts

Shebang Line

Create a script with the hash shebang:

#!/usr/local/bin/hash-shell

echo "Hello from hash!"

Make executable and run:

chmod +x script.sh
./script.sh

Direct Execution

hash-shell script.sh

Command String

hash-shell -c 'echo "Hello"; echo "World"'

From Standard Input

echo 'echo "Hello"' | hash-shell -s

Script Arguments

Positional Parameters

#!/usr/local/bin/hash-shell

echo "Script name: $0"
echo "First arg: $1"
echo "Second arg: $2"
echo "All args: $@"
echo "Arg count: $#"

Run:

./script.sh hello world
# Output:
# Script name: ./script.sh
# First arg: hello
# Second arg: world
# All args: hello world
# Arg count: 2

Parsing Options

getopts reads the options a script was given one at a time; shift then drops them so $1 is the first operand:

#!/usr/local/bin/hash-shell
verbose=0
while getopts "vo:" opt; do
    case $opt in
        v) verbose=1 ;;
        o) output=$OPTARG ;;
        ?) echo "usage: $0 [-v] [-o file] args" >&2; exit 2 ;;
    esac
done
shift $((OPTIND - 1))
echo "verbose=$verbose output=$output args=$*"
$ ./script.sh -v -o out.txt a b
verbose=1 output=out.txt args=a b

A letter followed by : in the option string takes an argument, attached (-oout.txt) or as the next word. Options can be clustered (-vo out.txt), and -- ends them. An unknown option or a missing argument sets opt to ? and prints a message; start the option string with : to get ? or : in opt and the offending letter in OPTARG instead, with no message.

Special Variables

VariableDescription
$0Script name
$1-$9Positional arguments
$#Number of arguments
$@All arguments (separate words)
$*All arguments (single word)
$?Exit code of last command
$$Process ID of shell

Functions

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

greet "World"

With return value:

is_even() {
    if [ $(($1 % 2)) -eq 0 ]; then
        return 0  # true
    else
        return 1  # false
    fi
}

if is_even 4; then
    echo "4 is even"
fi

Local Variables

local keeps a function’s variables out of the caller’s way. The previous value comes back when the function returns, an exported variable stays exported while it is shadowed, and a name given without a value is unset inside the function:

count=0
bump() {
    local count=10
    count=$((count + 1))
    echo "inside: $count"
}
bump
echo "outside: $count"
inside: 11
outside: 0

Scoping is dynamic, as in dash and bash: a function called from bump sees its count. local outside a function is an error.

A function may call itself, through eval and . too, 1000 levels deep by default. One level more fails with hash: f: maximum function nesting level exceeded (1000): the whole command is abandoned with status 1, an interactive shell shows the next prompt, and a script stops there. FUNCNEST changes the limit (FUNCNEST=50); FUNCNEST=0 removes the depth limit and leaves only the guard that refuses a call when the C stack is about to run out. Either way, runaway recursion ends with a message rather than a segmentation fault.

Variables

Assignment

NAME="value"        # No spaces around =
export NAME="value" # Export to environment

Expansion

echo $NAME          # Simple
echo ${NAME}        # Braced
echo "${NAME}"      # Quoted (preserves whitespace)

Exit Codes

#!/usr/local/bin/hash-shell

if [ ! -f "$1" ]; then
    echo "Error: File not found" >&2
    exit 1
fi

# Process file...
exit 0

Common codes:

  • 0 - Success
  • 1 - General error
  • 2 - Misuse of command

Comments

# This is a comment
echo "Hello"  # Inline comment

Best Practices

  1. Always quote variables: "$var" prevents word splitting
  2. Use meaningful names: FILE_COUNT not fc
  3. Check for errors: Test return codes
  4. Add comments: Explain complex logic
  5. Use exit codes: Return 0 for success
  6. Validate input: Check arguments first

Practical Example

#!/usr/local/bin/hash-shell

# Backup script
BACKUP_DIR="/backup"
DATE=$(date +%Y%m%d)

if [ ! -d "$BACKUP_DIR" ]; then
    mkdir -p "$BACKUP_DIR"
fi

for dir in /home/*; do
    if [ -d "$dir" ]; then
        user=$(basename "$dir")
        tar -czf "$BACKUP_DIR/${user}_${DATE}.tar.gz" "$dir"
        echo "Backed up: $user"
    fi
done

echo "Backup complete!"

See Also