Not all Bash scripts require arguments. However, it is extremely important to understand how
they are interpreted by Bash and how to use them. We have already executed Linux commands
with arguments. For example, when we run the command ls -l /var/log, both -l and /var/log
are arguments to the ls command.
Bash scripts are no different; we can supply command-line arguments and use them in our scripts:
1 | kali@kali:~$ cat ./arg.sh |
Here we created a simple Bash script, set executable permissions on it, and then ran it
with two arguments. The $1 and $2 variables represent the first and second arguments passed to
the script. Let’s explore a few special Bash variables:
| Variable Name | Description |
|---|---|
| $0 | The name of the Bash script |
| $1 - $9 | The first 9 arguments to the Bash script |
| $# | Number of arguments passed to the Bash script |
| $@ | All arguments passed to the Bash script |
| $? | The exit status of the most recently run process |
| $$ | The process ID of the current script |
| $USER | The username of the user running the script |
| $HOSTNAME | The hostname of the machine |
| $RANDOM | A random number |
| $LINENO | The current line number in the script |
Some of these special variables can be very useful when debugging a script. For example, we might
be able to obtain the exit status of a command to determine whether it was successfully executed
or not.