使用$1在脚本中调用bash函数


case ${1} in
"pkey") pkey ;;
"abserver") abserver ;;
"exitmenu") exitmenu ;;
"i3-binds") i3-binds ;;
esac

我有这个代码调用一个基于$1的脚本函数(作为参数传递给脚本)。是否有一种方法可以通过$1简单地调用有问题的函数并删除对case语句的需要?

我将使用这个来验证参数:

case $1 in
pkey|abserver|exitmenu|i3-binds) "$@" ;;
*) echo "Unknown function: $1" >&2 ;;
esac

我使用"$@"也将其他参数作为参数传递给函数。

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 -t "$1") == "function" ]] && "$@"||{ echo "error: '$1' undefined function"; exit 1; }

$ ./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