User Input & Arguments
Scripts rarely run with everything hardcoded — they take input either interactively while running, or as arguments typed right after the script's name.
Reading input while the script runs
read pauses the script and waits for the person running it to type something and press Enter:
bash ask.sh
#!/bin/bash read -p "What's your name? " name echo "Nice to meet you, $name."
Terminal output
What's your name? Priya Nice to meet you, Priya.
-p lets you show a prompt on the same line, instead of needing a separate echo before the read.
Command-line arguments
Arguments typed after a script's name are available inside it as $1, $2, and so on. $0 is the script's own name, and $# is the number of arguments given:
$ terminal
./greet.sh Priya Developer
bash greet.sh
#!/bin/bash echo "Script name: $0" echo "First arg: $1" echo "Second arg: $2" echo "Total args: $#"
Terminal output
Script name: ./greet.sh First arg: Priya Second arg: Developer Total args: 2
"$@" vs "$*"
Both represent "all the arguments," but they behave differently once you loop over them:
bash loop-args.sh
#!/bin/bash # called as: ./loop-args.sh "New York" Paris for arg in "$@"; do echo "Arg: $arg" done
Terminal output
Arg: New York Arg: Paris
Note:
"$@" (quoted) expands each argument as its own separate word, so "New York" stays together as one item. "$*" (quoted) instead joins everything into a single string. Almost always, "$@" is what you want when looping over arguments — it's the one that survives arguments containing spaces correctly.