【问题标题】:Arrays and Lists in Bourne ShellBourne Shell 中的数组和列表
【发布时间】:2011-09-16 05:17:27
【问题描述】:

我有密码

read input
case "$input" in
    "list"* )
        blah
        ;;

    "display"* )
        blah
        ;;

    "identify"* )
        blah
        ;;

    "rules"* )
        perl image.pl $input[1]
        ;;

    "quit" )
        echo "Goodbye!"
        ;;

    * )
        echo -n "Error, invalid command. "
        ;;

esac    

我试图弄清楚如何将 $input 的值传递给 image.pl 而不在输入中包含字符串“rules”。

即,如果用户输入“规则 -h”,我只想将“-h”传递给 image.pl。

与我的其他案例一样,我想测试一下输入中是否传递了任何其他参数,例如对于“退出”,我想测试用户是否说“退出 x”并抛出“退出”不接受任何其他“参数”的特定错误。

谢谢。

【问题讨论】:

  • 你是指 Bourne shell 还是 Bash?这方面的能力完全不同。值得注意的是,Bourne Shell 不包含数组。

标签: bash shell scripting sh


【解决方案1】:

假设您使用 Bourne shell 作为标题指定:

read input
set -- $input
case "$1" in
   list)
      blah
      ;;

    rules)
      perl image.pl "$2"
      ;;
esac

【讨论】:

  • 谢谢,这正是我想要的。如果允许,我会在 3 分钟内接受你的回答。
  • 您还可以使用“shift”内置命令删除$1,$2,..数组中的第一个元素。然后,只需将 "$*" 传递给 perl 脚本($* 是整个 $1,$2,.. 数组)。底线是 sh 仅支持 one 数组。
  • @nimrodm:您应该更喜欢"$@" 而不是"$*",除非您特别希望shell 压缩任何特殊引用。你仍然得到我的 +1。
  • 谢谢@nimrodm,我只是认为这是一个问题,之前给我的解决方案并不是我所需要的,因为我仍然希望能够通过其余的命令。所以谢谢你:)
【解决方案2】:

你可以使用$input变量在bash中初始化一个数组,代码如下:

read input
declare -a arr=($input)
case "${arr[0]}" in
    "list")
        blah
        ;;
    "display")
        blah
        ;;
    "identify")
        blah
        ;;
    "rules")
        shift
        perl image.pl ${arr[1]}
        ;;
    "quit")
        echo "Goodbye!"
        ;;
    *)
        echo -n "Error, invalid command. "
        ;;
esac 

【讨论】:

    猜你喜欢
    • 2012-11-09
    • 2011-06-12
    • 2011-01-13
    • 1970-01-01
    • 2015-05-28
    • 2015-12-03
    • 2011-01-07
    • 2014-04-12
    • 1970-01-01
    相关资源
    最近更新 更多