Command-line arguments are values passed to a Bash script when you run it from the terminal. They make Bash scripts more flexible because you do not need to edit the script every time you want to change input values.
For example, instead of hardcoding a username, file name, IP address, or directory path inside the script, you can provide it while running the script. Command-line arguments are commonly used in Linux automation, backup scripts, system administration, cybersecurity tools, and log analysis scripts.
In Bash, command-line arguments are accessed using special variables called positional parameters.
| Variable | Meaning |
|---|---|
$0 | Script name |
$1 | First argument |
$2 | Second argument |
$3 | Third argument |
$# | Total number of arguments |
$@ | All arguments |
For example:
./script.sh kali linux
Here, kali is $1 and linux is $2.
Create a new Bash script:
nano arguments.sh
Add the following code:
#!/bin/bashecho "Script name: $0"echo "First argument: $1"echo "Second argument: $2"
Save the file and give execute permission:
chmod +x arguments.sh
Run the script with arguments:
./arguments.sh Kali Linux
Output:
Script name: ./arguments.shFirst argument: KaliSecond argument: Linux
Here is a practical example:
#!/bin/bashname=$1topic=$2echo "Hello, $name"echo "You are learning $topic"
Run it:
./arguments.sh "Kali User" "Bash Scripting"
Output:
Hello, Kali UserYou are learning Bash Scripting
Use quotes when an argument contains spaces.
You can use $# to check how many arguments were passed.
#!/bin/bashif [[ $# -lt 2 ]]; then echo "Usage: $0 username target" exit 1fiusername=$1target=$2echo "Username: $username"echo "Target: $target"
Run it:
./script.sh admin 192.168.1.1
This is useful for preventing script errors when required values are missing.
You can process all arguments using $@.
#!/bin/bashecho "Arguments provided:"for arg in "$@"do echo "- $arg"done
Run it:
./script.sh nmap curl grep awk
Output:
Arguments provided:- nmap- curl- grep- awk
#!/bin/bashif [[ $# -ne 1 ]]; then echo "Usage: $0 target-ip" exit 1fitarget=$1echo "Scanning target: $target"nmap "$target"
Run it:
./scan.sh 192.168.1.1
This script accepts the target IP address from the command line.
Command-line arguments are an important part of Bash scripting. They allow you to pass values to a script when running it, making your scripts more dynamic and reusable.
For beginners, learning $1, $2, $#, and $@ is very useful. These variables help you build better Bash scripts for automation, file handling, backups, Linux administration, and cybersecurity tasks.