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