Command-line arguments, also known as command-line parameters, are the values passed to a program or script when it is invoked from the command line. They allow you to provide input or instructions to the program at runtime, influencing its behaviour or providing data for processing.
In Bash, command-line arguments are accessed through special variables:
$0
: Represents the name of the script or shell itself.$1
,$2
,$3
, …: These variables hold the positional parameters passed to the script or function.$1
represents the first parameter,$2
represents the second parameter, and so on.$#
: Holds the number of positional parameters passed to the script or function.$@
: Represents all the positional parameters passed to the script or function as separate arguments.$*
: Represents all the positional parameters passed to the script or function as a single string.
When executing a script or command from the command line, you can provide command-line arguments after the script or command name, separated by spaces. For example:
./my_script.sh arg1 arg2 arg3
In this example, arg1
, arg2
, and arg3
are the command-line arguments passed to the script my_script.sh
. Inside the script, you can access these arguments using the positional parameter variables $1
, $2
, and $3
, respectively.
Here’s an example script that demonstrates accessing and using command-line arguments:
#!/bin/bash
echo "The script name is: $0"
echo "The first argument is: $1"
echo "The second argument is: $2"
echo "The number of arguments is: $#"
echo "All arguments as separate values: $@"
echo "All arguments as a single string: $*"
When running this script with command-line arguments, you will see the values being printed based on the provided arguments.
Command-line arguments provide a way to make your scripts and programs more flexible and configurable. They allow users to pass input or parameters to the script when executing it, enabling customization and dynamic behaviour.