带有 bash 的子命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13638248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 03:53:58  来源:igfitidea点击:

Sub-commands with bash

bashsubcommand

提问by LavaScornedOven

Is it possible to implement sub-commands for bash scripts. I have something like this in mind:

是否可以为 bash 脚本实现子命令。我有这样的想法:

http://docs.python.org/dev/library/argparse.html#sub-commands

http://docs.python.org/dev/library/argparse.html#sub-commands

回答by rici

Here's a simple unsafe technique:

这是一个简单的不安全技术:

#!/bin/bash

clean() {
  echo rm -fR .
  echo Thanks to koola, I let you off this time,
  echo but you really shouldn\'t run random code you download from the net.
}

help() {
  echo Whatever you do, don\'t use clean
}

args() {
  printf "%s" options:
  while getopts a:b:c:d:e:f:g:h:i:j:k:l:m:n:o:p:q:r:s:t:u:v:w:x:y:z: OPTION "$@"; do
    printf " -%s '%s'" $OPTION $OPTARG
  done
  shift $((OPTIND - 1))
  printf "arg: '%s'" "$@"
  echo
}

"$@"

That's all very cool, but it doesn't limit what a subcommand could be. So you might want to replace the last line with:

这一切都非常酷,但它并没有限制子命令可以是什么。因此,您可能希望将最后一行替换为:

if [[  =~ ^(clean|help|args)$ ]]; then
  "$@"
else
  echo "Invalid subcommand " >&2
  exit 1
fi

Some systems let you put "global" options before the subcommand. You can put a getoptsloop before the subcommand execution if you want to. Remember to shiftbefore you fall into the subcommand execution; also, reset OPTINDto 1 so that the subcommands getopts doesn't get confused.

某些系统允许您在子命令之前放置“全局”选项。getopts如果需要,您可以在子命令执行之前放置一个循环。shift在陷入子命令执行之前,请记住;此外,重置OPTIND为 1 以便子命令 getopts 不会混淆。