加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

linux – 定义在bash中接受参数的子命令

发布时间:2020-12-14 01:20:36 所属栏目:Linux 来源:网络整理
导读:所以我想创建一个“程序”来促进像yum命令和其他命令…当程序完成时我想把它放在/usr/bin中,名字叫“dafs” 我用这个例子测试了文件名为dafs #!/bin/bash$1 $2 $3function yum { function maintenance { yum -y update yum -y upgrade yum clean all } funct
所以我想创建一个“程序”来促进像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

注意事项:

>“$@”扩展到传递给范围中当前项的参数的完整列表,保留参数边界并避免全局扩展(与$*和未加引号的$@不同).
> shift将第一个参数($1)从列表前面弹出,使新值“$@”比旧列表短一个.
>当没有子命令存在时,内置命令会导致调用真实的yum命令,而不是简单地再次递归到yum函数.
> declare -f funcname如果真的传递了一个函数,则返回true(并打印该函数的定义).相反,如果传递任何类型的runnable命令,则返回true.因此,使用类型“yum __ $cmdname”允许将yum__foo定义为外部脚本或任何其他类型的命令,而不仅仅是函数,而稍后完成的declare -f“$1”仅允许运行函数.

最后要考虑的是,如果你不打算支持获取源代码,那么将遗漏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

在这种情况下,始终搜索由前两个参数命名的子命令,后跟仅由第一个参数命名的函数.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读