Concept Flow - Command-line arguments ($1, $2, ...)
Start script
Read $1
Read $2
... Read $n
Use arguments in script
End script
The script starts and reads each command-line argument in order ($1, $2, ...), then uses them as needed before ending.
#!/bin/bash echo "First argument: $1" echo "Second argument: $2"
| Step | Action | Value of $1 | Value of $2 | Output |
|---|---|---|---|---|
| 1 | Start script | apple | banana | |
| 2 | Print first argument | apple | banana | First argument: apple |
| 3 | Print second argument | apple | banana | Second argument: banana |
| 4 | End script | apple | banana |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|---|
| $1 | unset | apple | apple | apple | apple |
| $2 | unset | banana | banana | banana | banana |
Command-line arguments in bash are accessed as $1, $2, etc. $0 is the script name. Arguments are strings passed after the script name. Use them to customize script behavior. If no argument is given, $n is empty. Example: echo "$1" prints the first argument.
$1 represent in a bash script?$1 refers to the first argument given after the script name.$# is the count of arguments, $0 is the script name, and $@ is all arguments.$1 = first argument [OK]$1 for the first, so the third argument is $3.$2 is second argument, $# is count, $0 is script name../script.sh apple banana cherry?
echo "First: $1" echo "Second: $2" echo "Count: $#"
echo "Argument 1: $1" echo "Argument 2: $2"What is the error if you run the script without any arguments?
$1, $2, etc. Which approach works best?shift moves arguments left, so $1 becomes next argument each time.echo $@ to print all arguments on one line prints all on one line; Use $0 to print all arguments one by one prints script name; Use shift command in a loop to access each argument and print it correctly loops and prints each argument on new line.shift command in a loop to access each argument and print it -> Option BPass the test and this pattern moves unknown