linux - 如何在命令行中从脚本运行函数?

我有一个脚本,它有一些功能。

我可以直接从命令行运行其中一个函数吗?

这样的?

myScript.sh func()

最佳答案

好吧,虽然其他答案是正确的 - 你当然可以做其他事情:如果你可以访问 bash 脚本,你可以修改它,只需将特殊参数放在末尾 "$@" - 将扩展为您指定的命令行的参数,并且由于它是“单独的”,shell 将尝试逐字调用它们;在这里您可以将函数名称指定为第一个参数。示例:

$ cat test.sh
testA() {
  echo "TEST A $1";
}

testB() {
  echo "TEST B $2";
}

"$@"


$ bash test.sh
$ bash test.sh testA
TEST A 
$ bash test.sh testA arg1 arg2
TEST A arg1
$ bash test.sh testB arg1 arg2
TEST B arg2

对于波兰语,可以先验证该命令是否存在并且是一个函数:

# Check if the function exists (bash specific)
if declare -f "$1" > /dev/null
then
  # call arguments verbatim
  "$@"
else
  # Show a helpful error
  echo "'$1' is not a known function name" >&2
  exit 1
fi

https://stackoverflow.com/questions/8818119/

相关文章:

c - 如何在 C 中与 Linux 一起使用共享内存

python - 根据数据类型获取 pandas 数据框列的列表

python - 如何在 Python 中实现树?

linux - 如何找到我使用的 Fedora 版本?

python - 重命名 virtualenv 文件夹而不破坏它

linux - 如何在 Linux shell 脚本中插入新行?

python - _tkinter.TclError : no display name and n

python - 拆分(分解) Pandas 数据框字符串条目以分隔行

linux - 用于计算已用时间的 Bash 脚本

python - 减少matplotlib图中的左右边距