Bash function arguments and return values are important for writing reusable and powerful Bash scripts. A function becomes more useful when you can pass values to it and get a result back. Instead of writing separate code for every task, you can create one function and use it with different inputs.
If you are learning Bash scripting, understanding function arguments and return values will help you build cleaner scripts for Linux automation, system checks, backups, cybersecurity tasks, and command-line tools.
Bash function arguments are values passed to a function when calling it. Inside the function, you can access these values using positional parameters.
| Parameter | Meaning |
|---|---|
$1 | First argument |
$2 | Second argument |
$3 | Third argument |
$@ | All arguments |
$# | Number of arguments |
Create a script:
nano function-arguments.sh
Add the following code:
#!/bin/bashgreet_user() { echo "Hello, $1" echo "Welcome to $2"}greet_user "Kali User" "Bash Scripting"
Save and run it:
chmod +x function-arguments.sh./function-arguments.sh
Output:
Hello, Kali UserWelcome to Bash Scripting
Here, $1 receives Kali User, and $2 receives Bash Scripting.
You can pass many values to a Bash function.
#!/bin/bashshow_info() { echo "Username: $1" echo "Tool: $2" echo "Website: $3"}show_info "admin" "Nmap" "kalilinuxtutorials.com"
This is useful when you want one function to work with different users, tools, files, or directories.
To print all arguments, use $@.
#!/bin/bashprint_tools() { echo "Security tools:" for tool in "$@" do echo "- $tool" done}print_tools nmap curl netcat nikto
Output:
Security tools:- nmap- curl- netcat- nikto
In Bash, the return command is mainly used to return an exit status, not normal text. A return value should usually be between 0 and 255. In Linux, 0 means success, and non-zero means failure.
Example:
#!/bin/bashcheck_file() { if [[ -f "$1" ]]; then return 0 else return 1 fi}check_file "/etc/passwd"if [[ $? -eq 0 ]]; then echo "File exists"else echo "File does not exist"fi
The $? variable stores the return status of the last command or function.
To return text, use echo and capture the output.
#!/bin/bashget_user() { echo "$(whoami)"}current_user=$(get_user)echo "Current user is: $current_user"
This is the best method when you want a function to send back a string or command output.
Bash function arguments and return values make scripts more flexible and reusable. You can pass values using $1, $2, $@, and check function status using return and $?.
For beginners, this is an important Bash scripting skill. It helps you create better automation scripts, Linux tools, cybersecurity checks, and reusable command-line functions.