【问题标题】:A shell script "getopts error"一个 shell 脚本“getopts 错误”
【发布时间】:2014-10-16 23:09:04
【问题描述】:

我有这个代码:

#!/bin/bash
if [ $# -lt 2 ]; then
    echo "usage: $0 <-lu> <string>"
    exit 1
fi
while getopts "lu" OPT
do
    case $OPT in
        u) casechange=0;;
        l) casechange=1;;
        *) echo "usage: -u<upper> || -l<lower> <string>";
            exit 1;;
    esac
done
shift $(( $optind -1 ))
if [ $casechange -eq 0 ]; then
    tr '[A-Z]' '[a-z]' <$string
elif [ $casechange -eq 1 ]; then
    tr '[a-z]' '[A-Z]' <$string
else
    echo "fatal error"
    exit 1
fi

我收到两个错误:

  • line 15: shift -1: shift count out of range
  • line 19: $string: ambiguous redirect

我做错了什么?我该如何解决这个问题?

【问题讨论】:

  • 你在哪里定义$string
  • 显然没有。

标签: bash shell unix getopts


【解决方案1】:

OPTIND 必须是大写字母。 Bash 默认区分大小写。这使得 $optind 为空,而您实际上是在尝试移动 -1。

此外,在处理完选项后,您需要对非选项参数做一些事情: string="$1"

然后tr '[A-Z]' '[a-z]' &lt;&lt;&lt;"$string" 用于从变量重定向。 最后,你的悲伤路径输出应该是stderr (&gt;&amp;2)。

所有组合(+一些小的改进):

#!/bin/bash
if [[ $# -lt 2 ]]; then
    echo "usage: $0 <-lu> <string>" >&2
    exit 1
fi
while getopts "lu" OPT
do
    case $OPT in
        u) casechange=0;;
        l) casechange=1;;
        *) echo "usage: -u<upper> || -l<lower> <string>" >&2;
            exit 1;;
    esac
done
shift $(( $OPTIND -1 ))
string="$1"
if [[ "$casechange" -eq 0 ]]; then
    tr 'A-Z' 'a-z' <<<"$string"
elif [[ "$casechange" -eq 1 ]]; then
    tr 'a-z' 'A-Z' <<<"$string"
else
    echo "fatal error" >&2
    exit 1
fi

【讨论】:

  • 进行该更改后,我仍然在该行收到错误消息。 > 第 15 行:expr 2 -1:表达式中的语法错误(错误标记为“2 -1”)
  • 它在您的评论上方列出 > 第 15 行:expr 2 -1:表达式中的语法错误(错误标记为“2 -1”)
  • @tinfoil_powers:我不是指错误信息。我的意思是你的代码行。
  • 第 15 行如下:>shift $((expr $OPTIND -1))
  • 你不需要在那里发臭expr。双括号处理数学运算,无需调用外部程序。就像括号可以让你在不调用外部test 程序的情况下通过。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-06
  • 1970-01-01
  • 2019-03-21
  • 2014-11-10
相关资源
最近更新 更多