Intermediate · 7 min · practise every command in the built-in terminal

Script Arguments

Positional parameters

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

Run: ./script.sh hello world

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

Check argument count

#!/bin/bash
if [ $# -ne 2 ]; then
    echo "Usage: $0 <source> <destination>"
    exit 1
fi

SRC=$1
DST=$2
echo "Copying $SRC to $DST"
cp "$SRC" "$DST"

shift — consume arguments

while [ $# -gt 0 ]; do
    echo "Argument: $1"
    shift          # Remove first argument, rest shifts left
done

getopts — flag parsing

while getopts ":n:v" opt; do
    case $opt in
        n) NAME="$OPTARG" ;;
        v) VERBOSE=true ;;
        \?) echo "Invalid option: -$OPTARG" && exit 1 ;;
    esac
done

Run: ./script.sh -n IVski -v

Practice tasks

  1. Write a script that takes a filename as argument and prints how many lines it has
  2. Write a script that prints all arguments passed to it
  3. Check the number of arguments before running your script logic

Commands in this lesson

Shell Scripting