Reputation:
I would like to write a Bash function that uses named input parameters instead of positional parameters (eg. ${0}
or ${1}
). Is this possible, and if so, how do I achieve this?
Upvotes: 3
Views: 2763
Reputation: 42711
Just reassign the parameters to something more intuitive:
function test {
local foo=$1
local bar=$2
local baz=$3
local msg='Function got called with parameters %s, %s, and %s\n'
printf "$msg" "$foo" "$bar" "$baz"
}
If you're looking for something to make calling the function more user-friendly, look into getopt
.
Upvotes: 3
Reputation: 715
You can use getopts builtin to assign values to a one-letter-named parameters:
doSomething () {
local key
local -A param
while getopts ': a: b: c' key; do
param[$key]=${OPTARG:-1}
done
declare -p param
}
doSomething -a 'Be Patient' \
-b 'ThinkBeforeYouGo' \
-c
After "while" cycle in doSomething you will have:
param=( [a]="Be Patient" [b]="ThinkBeforeYouGo" [c]="1" )
You can use getopt instead of getopts to process "long" keys, but getopt is not BASH builtin and, unfortunately (and unlike very simple and intuitive getopts), it is too complex and heavy to use in most cases.
Upvotes: 0
Reputation: 2460
Not out of the box, not the way you'd like. Every bash scripter runs in to this pretty quickly.
If you need the script to work on more than one machine, you pretty much have to roll your own solution. If it only has to work in one environment, you can load it up with dependencies and make your life easier.
A quick google for 'bash named parameters' will turn up a myriad of resources whichever way you want to go.
Upvotes: 0