Back to Blog

Master shell scripting fundamentals on Mac and Linux terminals

Sandy LaneSandy Lane

Video: Master shell scripting fundamentals on Mac and Linux terminals by Taught by Celeste AI - AI Coding Coach

Watch full page →

Master shell scripting fundamentals on Mac and Linux terminals

Shell scripting lets you automate tasks and create powerful workflows on Mac and Linux terminals. This guide covers creating executable scripts, using variables, writing conditional statements, and implementing loops to handle repetitive tasks efficiently.

Code

#!/bin/bash
# Example script demonstrating basics of shell scripting

# Creating and using variables
NAME='John'
echo "Hello, $NAME"

# Command substitution: store current date in a variable
CURRENT_DATE=$(date)
echo "Today is $CURRENT_DATE"

# Conditional statements: check if a file exists
FILE="example.txt"
if [ -f "$FILE" ]; then
  echo "File '$FILE' exists."
elif [ -d "$FILE" ]; then
  echo "'$FILE' is a directory."
else
  echo "'$FILE' does not exist."
fi

# Numeric comparison
NUM=5
if [ $NUM -gt 3 ]; then
  echo "$NUM is greater than 3"
fi

# For loop: iterate over a list
for NAME in Alice Bob Charlie; do
  echo "Hello, $NAME"
done

# For loop with brace expansion
for i in {1..5}; do
  echo "Number $i"
done

# C-style for loop
for ((i=1; i<=3; i++)); do
  echo "C-style loop iteration $i"
done

# While loop with counter
counter=1
while [ $counter -le 3 ]; do
  echo "Counter: $counter"
  ((counter++))
done

# Loop through all .sh files in current directory
for script in *.sh; do
  [ -e "$script" ] || continue  # Skip if no .sh files
  echo "Found script: $script"
done

Key Points

  • Start scripts with a shebang (#!/bin/bash) to specify the shell interpreter.
  • Make scripts executable using chmod +x script.sh and run them with ./script.sh or bash script.sh.
  • Use variables without spaces around the equal sign and access them with a dollar sign prefix (e.g., $NAME).
  • Write conditional statements with if [ condition ]; then ... fi and use file, string, and numeric tests for decision making.
  • Use loops (for and while) to automate repetitive tasks, including iterating over lists, sequences, and files.