How do I format in a script the number of arguments passed through a bash script? This what I have currently that works:
#!/bin/bash
echo "$# parameters"
echo "$@"
But I wanted to format is using a function but everytime I run it, it comes back as 0 parameters:
#!/bin/bash
example()
{
echo "$# parameters"; echo "$@";
}
example
Am I thinking about this incorrectly?
You are not passing the arguments to your function.
#! /bin/bash
EXE=`basename $0`
fnA()
{
echo "fnA() - $# args -> $@"
}
echo "$EXE - $# Arguments -> $@"
fnA "$@"
fnA five six
Output:
$ ./bash_args.sh one two three
bash_args.sh - 3 Arguments -> one two three
fnA() - 3 args -> one two three
fnA() - 2 args -> five six
It's the POSIX standard not to use the function
keyword. It's supported in bash
for ksh
compatibility.
EDIT: Quoted "$@"
as per Gordon's comment - This prevents reinterpretation of all special characters within the quoted string
The second one should work. Following are few similar examples I use every day that has the same functionality.
function dc() {
docker-compose $@
}
function tf(){
if [[ $1 == "up" ]]; then
terraform get -update
elif [[ $1 == "i" ]]; then
terraform init
else
terraform $@
fi
}
function notes(){
if [ ! -z $1 ]; then
if [[ $1 == "header" ]]; then
printf "\n$(date)\n" >> ~/worknotes
elif [[ $1 == "edit" ]]; then
vim ~/worknotes
elif [[ $1 == "add" ]]; then
echo " • ${@:2}" >> ~/worknotes
fi
else
less ~/worknotes
fi
}
PS: OSX I need to declare function
you may not need that on other OSes like Ubuntu
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.