【问题标题】:utterly confused regarding bash script command line arguments对 bash 脚本命令行参数完全感到困惑
【发布时间】:2014-02-10 17:35:49
【问题描述】:

我有以下 bash 脚本文件 callee.sh,它是从另一个脚本文件 caller.sh 调用的。

被调用者.sh如下:

if [ $1 -eq  1 ];
then    
    echo  inside $1
    source ~/MYPROGRAMSRC/standAloneWordCount.sh $2
    #echo "inside standalone branch"
    #echo $1

elif [  $1 -eq  2  ];
then
    #echo "inside distributed branch"
    #echo $1

else
    echo invalid option for first argument-\n Options:\n "distributed"\n or\n "standalone"\n 


fi  

正如大多数人可能知道的那样,这是我用来根据参数决定是在分布式模式还是独立模式下运行 hadoop 的脚本。

这个脚本是从caller.sh调用的,如下

source callee.sh $2 $counterGlobal

其中 $2 是一个数字 1 或 2,$counterGlobal 是某个整数。

我的问题是 callee.sh 中的 if 条件永远不会评估为 True,因此我从 callee.sh 中调用的脚本 standAloneWordCount.sh 永远不会被调用。我正在使用 bash shell 运行并尝试了许多 if 语句的变体,例如:

if [ $(($1 == 1 )) ]  -- (1)

在 -- (1) 行上方的 echo 语句中,表达式 $(($1 == 1)) 的计算结果为 1,所以我很困惑为什么我无法满足 if 条件。

我也不断收到错误提示:

syntax error near unexpected token `else'

如果有人可以帮助我解决这两个错误,将不胜感激。因为我的想法已经用完了。

提前致谢!

【问题讨论】:

    标签: linux bash shell hadoop command-line-arguments


    【解决方案1】:

    尝试了许多 if 语句的变体,例如:

    if [ $(($1 == 1 )) ]

    你应该说:

    if (($1 == 1)); then
      ...
    fi
    

    关于Syntax error near unexpected tokenelse'`,这不是因为您上面显示的任何代码。它似乎来自脚本的其他部分。

    【讨论】:

    • 好吧,实际上发现还有其他问题,因为每次我关闭并重新打开文件时它一直说出现问题并且正在使用 .swp 文件。所以我删除了 .swp 文件,您的解决方案有效。谢谢。
    【解决方案2】:

    如果您使用的是 bash,请尝试使用双方括号:

    if [[ $1 -eq 1 ]]; then
        echo "inside 1"
    fi
    

    至于syntax error,您需要在文本周围加上引号(这也意味着转义现有引号或使用单引号):

    echo -e "invalid option for first argument-\n Options:\n \"distributed\"\n or\n \"standalone\"\n"
    

    -e 标志用于让 bash 知道您希望 \n 评估为换行符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-03
      • 2018-08-11
      • 1970-01-01
      • 2015-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多