case ${1} in
"pkey") pkey ;;
"abserver") abserver ;;
"exitmenu") exitmenu ;;
"i3-binds") i3-binds ;;
esac
I have this code to call a function in a script based on $1 (passed as an argument to script). Is there a way to simply call the function in question via $1 and remove the need for case statement?
CodePudding user response:
I would use this to validate the parameter:
case $1 in
pkey|abserver|exitmenu|i3-binds) "$@" ;;
*) echo "Unknown function: $1" >&2 ;;
esac
I used "$@"
to also pass the other parameters as arguments to the function.
CodePudding user response:
script.sh
#!/bin/bash
func1(){ echo "${FUNCNAME[0]} executed with arg1: $1"; }
func2(){ echo "${FUNCNAME[0]} executed with args: $@"; }
func3(){ echo "${FUNCNAME[0]} executed with arg2: $2"; }
type "$1" 2>&1|grep -q function && "$@"||{ echo "error: '$1' undefined function"; exit 1; }
Test
$ ./script.sh func1 "1 2 3" a b
func1 executed with arg1: 1 2 3
$ ./script.sh func2 "1 2 3" a b
func2 executed with args: 1 2 3 a b
$ ./script.sh func3 "1 2 3" a b
func3 executed with arg2: a
$ ./script.sh foo "1 2 3" a b
error: 'foo' undefined function
$ ./script.sh
error: '' undefined function