【问题标题】:Making a CLI command using an SH script [closed]使用 SH 脚本制作 CLI 命令 [关闭]
【发布时间】:2013-09-26 08:21:18
【问题描述】:

我想使用 .sh 文件制作 Pathogen 帮助程序脚本。我知道如果你让它可执行,它可以作为命令运行,但我不知道怎么做 -o --optionsarguments 或类似的东西。

基本上这就是我想要回答的问题,我真正需要知道的是如何做这样的事情:

pathogen install git://...

或者类似的东西。任何帮助表示赞赏。 :)

【问题讨论】:

  • Obligatory link. 你的问题太宽泛了,任何答案都可能超出你的专业水平。我建议你至少学习一下 shell 脚本的基础知识,或者像每个 Git-lovin' Pathogen 用户一样做$ git clone git://...
  • @romainl 我会检查那个链接,我不知道它,即使我为这些东西做了谷歌。谢谢!

标签: shell vim


【解决方案1】:

传递参数是两者中最简单的(参见 SO 上的“What are special dollar sign shell variables?”):

#!/bin/sh
echo "$#"; # total number of arguments
echo "$0"; # name of the shell script
echo "$1"; # first argument

假设文件名为“stuff”(无扩展名)并且运行./stuff hello world的结果:

3
stuff
hello

传入单个字母开关(带有可选的关联参数),例如./stuff -v -s hello 你会想使用getopts。请参阅 SO 上的“How do you use getopts”和this great tutorial。这是一个例子:

#!/bin/sh
verbose=1
string=
while getopts ":vs:" OPT; do
    case "$OPT" in
        v) verbose=0;;
        s) string="$OPTARG";;
    esac;
done;
if verbose; then
    echo "verbose is on";
fi;
echo "$string";

getopts 加上while 的行需要进一步解释:

  • while - 启动 while 循环,遍历所有内容 getopts 在处理后返回
  • getopts :vs: OPT; - 程序 getopts 有 2 个参数 :vs:OPT
    • getopts - 返回 while 可以迭代的东西
    • :vs: - 第一个参数,它描述了 getopts 在解析 shell 行时将寻找什么开关
      • : - 第一个冒号使 getopts 退出调试模式,省略它以使 getopts 详细
      • v - 找到开关-v,后面不会有参数,只是一个简单的开关
      • s: - 找到 -s 选项,后面有一个参数
    • OPT - 将存储使用的字符(开关的名称),例如“v”或“s”
  • OPTARG - 在 while 的每次迭代期间将值加载到其中的变量。对于v$OPTARG 将没有值,但对于s,它将。

冒号: 告诉getopts 在切换后寻找参数。唯一的例外是如果字符序列以: 开头,那么它将getopts 切换进/出调试/详细模式。例如:

getopts :q:r:stu:v 将使 getopts 退出调试模式,并告诉它开关 qru 将需要 args,而 stu 不会吨。这适用于:stuff -q hello -r world -s -t -u 123 -v

getopts tuv 只会告诉 getopts 搜索开关 tuv,不带参数,例如stuff -t -u -v,并且是冗长的

【讨论】:

  • 感谢您的回答!每当我弄清楚时,我都会接受其中之一。我会接受最有帮助的。 :)
  • 没问题,别忘了让你的shell脚本可执行chmod +x stuff,你可以考虑为你的shebang使用bash#!/bin/bash
【解决方案2】:

据我所知,内置的 bash getopts 不处理长 arg 解析机制。

getopt(1) 是您正在寻找的工具。

不完全是一个程序,但你会明白的

PARSED_OPTIONS=$(getopt -n "$0"  -o h123: --long "help,one,two,three:"  -- "$@")
while true;
do
  case "$1" in

    -h|--help)
      echo "usage $0 -h -1 -2 -3 or $0 --help --one --two --three"
     shift;;

    -1|--one)
      echo "One"
      shift;;

    --)
      shift
      break;;
  esac
done

看看here给出的代码示例和解释。

【讨论】:

  • 感谢您的回答!每当我弄清楚时,我都会接受其中之一。我会接受最有帮助的。 :)
猜你喜欢
  • 1970-01-01
  • 2017-08-02
  • 1970-01-01
  • 1970-01-01
  • 2012-08-18
  • 2012-11-20
  • 1970-01-01
  • 2012-12-31
  • 2016-05-19
相关资源
最近更新 更多