bash how to pass arguments

Answer

Special shell variable "$@" represents list of all arguments that is passed to script.

If you want to pass all arguments to your function, you can use this syntax:

function_name "$@"

If you want to pass all arguments to other script, you can use this syntax:

script_mame "$@"

Let's take an example called passit.sh. In this script, we defined function print_argument, that print arguments that comes from command line:

#!/bin/bash
	
# function's definition
function PRINT_ARGUMENTS()
{
echo "Arguments of shell are: $@"
}
	
	
# in this place we want to call function
PRINT_ARGUMENTS "$@"
	

Let's try to execute passit.sh in this way:

chmod u+x ./passit.sh
./passit.sh aa bb cc

Output: Arguments of shell are: aa bb cc

You can see that function obtains all shell arguments, which was written in the bash command line.

To get number of arguments use:

echo "Number of arguments of shell are: $#"

It is often used to check if required number are equal some value.

Was this information helpful to you? You have the power to keep it alive.
Each donated € will be spent on running and expanding this page about UNIX Shell.