☼
⌃
☰

Bash Scripting

Table of Contents

Bash Scripting

Bash (Bourne Again SHell) is a command-line interpreter and scripting language commonly used in Linux and macOS environments. Bash scripts are text files containing a sequence of commands that are executed by the Bash interpreter as if they were typed at the command prompt. They are powerful for automating tasks, managing system configurations, and creating custom commands.

Basic Structure

A Bash script is a plain text file. The first line, known as the "shebang," specifies the interpreter to be used. For Bash scripts, this is typically #!/bin/bash.

SH
#!/bin/bash
# This is a comment. The script will ignore this line.

# Commands are executed sequentially
echo "Starting the script..."
ls -l
echo "Script finished."

To run the script, you must first make it executable:

chmod +x your_script_name.sh

And then execute it:

./your_script_name.sh

Variables

Variables store data. There are no data types. A variable in Bash can contain a number, a character, or a string of characters.

To assign a value, use variable_name"value". Note there are no spaces around the equals sign. To access the value, use the dollar sign =$ before the name.

SH
#!/bin/bash

GREETING="Hello, Gregory"
echo $GREETING

# Using braces is safer, especially for concatenation
echo "${GREETING}! Welcome to Bash scripting."

Special Variables

  • $0 - The name of the script.
  • $1 to $9 - The first nine arguments to the script.
  • $@ - All the arguments.
  • $# - The number of arguments.
  • $? - The exit status of the last command executed. 0 means success.

Control Flow

Control flow statements allow your script to make decisions and loop over commands.

If/Else/Elif

Conditionally execute code based on an expression.

SH
#!/bin/bash

if [ "$1" == "Gregory" ]; then
  echo "Hello, Gregory."
elif [ -z "$1" ]; then
  echo "You didn't provide an argument."
else
  echo "Hello, $1."
fi

For Loops

Iterate over a list of items.

SH
#!/bin/bash

# Loop over a range of numbers
for i in {1..5}; do
  echo "Number: $i"
done

# Loop over files in the current directory
for FILE in *; do
  echo "File found: $FILE"
done

While Loops

Execute a block of code as long as a condition is true.

SH
#!/bin/bash

COUNT=1
while [ $COUNT -le 5 ]; do
  echo "Count: $COUNT"
  # Use double parentheses for arithmetic
  ((COUNT++))
done

Case Statements

A simpler way to write a series of if statements.

SH
#!/bin/bash

case "$1" in
  "start")
    echo "Starting service..."
    ;;
  "stop")
    echo "Stopping service..."
    ;;
  "restart")
    echo "Restarting service..."
    ;;
  *)
    echo "Usage: $0 {start|stop|restart}"
    ;;
esac

Functions

Functions group reusable pieces of code.

SH
#!/bin/bash

# Function definition
greet() {
  # Functions can access arguments with $1, $2, etc.
  echo "Hello, $1"
}

# Calling the function
greet "World"
greet "Gregory"

Input/Output And Pipes

  • Input/Output Redirection: Control where command output goes and where input comes from.
    • >: Redirect standard output, overwriting the destination file. (ls > file_list.txt)
    • >>: Redirect standard output, appending to the destination file. (echo "Log message" >> app.log)
    • <: Redirect standard input from a file. (sort < unsorted_names.txt)
  • Pipes (|): Send the output of one command as the input to another.
    • ps aux | grep "chrome"

Command Substitution

Capture the output of a command into a variable. The modern syntax is $(command).

SH
#!/bin/bash

CURRENT_DATE=$(date +"%Y-%m-%d")
echo "Today's date is: $CURRENT_DATE"

# Create a dated backup directory
BACKUP_DIR="backup-$CURRENT_DATE"
mkdir "$BACKUP_DIR"
echo "Created directory: $BACKUP_DIR"

Debugging

To see what your script is doing as it runs, you can use set -x. This will print each command to the terminal before it is executed, with variables expanded.

SH
#!/bin/bash
set -x # Start debugging from this point

USER="Gregory"
echo "Hello, $USER"

set +x # Stop debugging
echo "This part is not traced."