Back to Blog

Zsh read, $1, getopts Explained - Shell Scripting Tutorial (Lesson 8)

Sandy LaneSandy Lane

Video: Zsh read, $1, getopts Explained - Shell Scripting Tutorial (Lesson 8) by Taught by Celeste AI - AI Coding Coach

Watch full page →

Zsh read, $1, getopts Explained - Shell Scripting Tutorial (Lesson 8)

Learn how to interact with users and handle script arguments in Zsh by using the read command, positional parameters like $1, and option parsing with getopts. This tutorial covers reading input with prompts, accessing special variables, setting default values, and parsing command-line options effectively.

Code

# Reading user input with a prompt using Zsh's shorthand
read name?Enter your name: 
echo "Hello, $name!"

# Reading user input with echo -n and read
echo -n "Enter your age: "
read age
echo "You are $age years old."

# Accessing script arguments
echo "First argument: $1"
echo "All arguments: $@"
echo "Number of arguments: $#"

# Using special variables
echo "Script name: $0"
echo "Last command exit status: $?"
echo "Current process ID: $$"

# Using default values with parameter expansion
username=${USER:-guest}
echo "Username is $username"

# Parsing options with getopts
while getopts ":a:b" opt; do
  case $opt in
    a)
      echo "Option -a triggered with argument: $OPTARG"
      ;;
    b)
      echo "Option -b triggered"
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      ;;
    :)
      echo "Option -$OPTARG requires an argument." >&2
      ;;
  esac
done

Key Points

  • The read command in Zsh can prompt inline using read var?prompt for concise input requests.
  • Positional parameters like $1, $@, and $# provide access to script arguments and their count.
  • Special variables $0, $?, and $$ give script name, last command status, and process ID respectively.
  • Parameter expansion with ${var:-default} allows setting default values when variables are unset or empty.
  • getopts simplifies option parsing in scripts, handling flags and their arguments robustly with OPTARG.