linux – 定义在bash中接受参数的子命令
所以我想创建一个“程序”来促进像yum命令和其他命令…当程序完成时我想把它放在/usr/bin中,名字叫“dafs”
我用这个例子测试了文件名为dafs #!/bin/bash $1 $2 $3 function yum { function maintenance { yum -y update yum -y upgrade yum clean all } function download { yum -y install --downloadonly $3 } } 但是当我运行./dafs yum维护或./dafs yum下载http它不起作用我猜,因为语法不正确.. 那么,我如何将参数传递给函数或子函数,如上面的例子? 解决方法
定义子命令的最佳实践方法是使用前缀命名空间和“启动器”功能.这就是git的用法,例如(对git foo和git bar使用git-foo和git-bar命令).
在这里,我使用双下划线而不是单个短划线作为分隔符,因为下划线(与破折号不同)在POSIX sh标准中被定义为在函数名称中有效. yum__maintenance() { command yum -y update command yum -y upgrade command yum clean all } yum__download() { command yum -y install --downloadonly "$@" } yum() { local cmdname=$1; shift if type "yum__$cmdname" >/dev/null 2>&1; then "yum__$cmdname" "$@" else command yum "$cmdname" "$@" # call the **real** yum command fi } # if the functions above are sourced into an interactive interpreter,the user can # just call "yum download" or "yum maintenance" with no further code needed. # if invoked as a script rather than sourced,call function named on argv via the below; # note that this must be the first operation other than a function definition # for $_ to successfully distinguish between sourcing and invocation: [[ $_ != $0 ]] && return # make sure we actually *did* get passed a valid function name if declare -f "$1" >/dev/null 2>&1; then # invoke that function,passing arguments through "$@" # same as "$1" "$2" "$3" ... for full argument list else echo "Function $1 not recognized" >&2 exit 1 fi 注意事项: >“$@”扩展到传递给范围中当前项的参数的完整列表,保留参数边界并避免全局扩展(与$*和未加引号的$@不同). 最后要考虑的是,如果你不打算支持获取源代码,那么将遗漏yum函数,但扩展你的启动器以识别子命令本身: if declare -f "${1}__$2" >/dev/null; then func="${1}__$2" shift; shift # pop $1 and $2 off the argument list "$func" "$@" # invoke our named function w/ all remaining arguments elif declare -f "$1" >/dev/null 2>&1; then "$@" else echo "Neither function $1 nor subcommand ${1}__$2 recognized" >&2 exit 1 fi 在这种情况下,始终搜索由前两个参数命名的子命令,后跟仅由第一个参数命名的函数. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |