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

Dio*_*iva 4 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
    }

}
Run Code Online (Sandbox Code Playgroud)

但是当我运行./dafs yum maintenance./dafs yum download http它不起作用我猜,因为语法不正确..

那么,我如何将参数传递给函数或子函数,如上面的例子?

Cha*_*ffy 6

定义子命令的最佳实践方法是使用前缀命名空间和"启动器"功能.这是怎么git做的,例如(使用git-foogit-bar命令的git foogit 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
Run Code Online (Sandbox Code Playgroud)

注意事项:

  • "$@"扩展到传递给范围中当前项的参数的完整列表,保留参数边界并避免全局扩展(不同于$*和不引用$@).
  • shift弹出$1列表前面的第一个参数(),使新值"$@"比旧列表短一个.
  • command内建导致真正yum被调用的命令,而不是简单的递归到的yum功能再次,当不存在子.
  • declare -f funcname如果真的传递了一个函数,则返回true(并打印该函数的定义).type相反,如果传递任何类型的runnable命令,则返回true .因此,使用type "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
Run Code Online (Sandbox Code Playgroud)

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

  • @DiogoSaraiva,我不关注 pastebin.com 的链接。尝试在没有广告拦截器的情况下查看该网站,您就会明白为什么——如果他们获得了适当的报酬,那么任何努力通过货币化的人都不会被信任不会托管恶意软件。考虑 https://gist.github.com/ 或 http://ix.io/。 (2认同)