【问题标题】:Unable to run the unix shell script无法运行 unix shell 脚本
【发布时间】:2014-09-01 14:52:31
【问题描述】:
    #!/bin/ksh
    echo -n "enter the 1 to convert lower to upper or 2 convert upper to lower"
    read n
    echo -in_str "Enter the string here"
    read in_str
    echo $n
    echo $in_str
    if [ $n -eq 1 ] then
        $ echo $in_str| awk '{print toupper($0)}'
    elif [ -n -eq 2 ] then
        $ echo $in_str| awk '{print tolower($0)}'
    else
        echo "please select the correct choice"
    fi

出现错误:否则我无法运行上述代码

【问题讨论】:

  • awk 的替代品是 typeset -u in_strtr '[:upper:]' '[:lower:]'

标签: shell unix ksh


【解决方案1】:

这个:

if [ $n -eq 1 ] then

需要这样:

if [ $n -eq 1 ]; then

或者这个:

if [ $n -eq 1 ]
then

【讨论】:

  • 非常感谢大家是 unix shell 脚本的新手
  • 假设$n 不为空(或为空,但通常不在读取后)。如果不是,则可以将${n:-9} 分配给 9(如果为空白/空),因此可以使用-eq
【解决方案2】:

then 之前需要分号。并且您还有额外的$ 符号。我想你想要这样的东西

if [ $n -eq 1 ]; then
    echo $in_str| awk '{print toupper($0)}'
elif [ $n -eq 2 ]; then
    echo $in_str| awk '{print tolower($0)}'
else
    echo "please select the correct choice"
fi

至少它似乎在这里工作。

【讨论】:

  • 实际上,我很确定您也需要在elif 上使用then
【解决方案3】:
$ echo $in_str| awk '{print toupper($0)}'

???

我认为您不希望该行前面的 $ 字符(或其他 echo 行)。

另外,如果你想让then和你的if在同一行,应该是:

if [ $n -eq 1 ] ; then

【讨论】: