【问题标题】:Equal and not equal operators not working in bash script等于和不等于运算符在 bash 脚本中不起作用
【发布时间】:2021-12-29 08:06:19
【问题描述】:

我在 .sh 脚本中有这个函数:

prepare_for_test(){
    stopresources;
    initresources;
    if [ "$1" = "--gf" ]; then
            startglassfish;
    fi
    docker ps;
    notify-send "Done!" "You can now test" -t 10000;
 };

脚本名称为 preparefortests.sh。当我在 bash 上运行它时,传递 --gf 或“--gf”:

preparefortests.sh --gf

它不运行别名 startglassfish,就好像那个 if 语句是假的一样。 我什至尝试添加对参数的检查:

if [ "$1" ] && [ "$1" != "--gf" ]; then
  echo "uknown parameter $1"
fi

但它也不起作用,例如我尝试像这样运行它:

preparefortests.sh hello

我希望“未知参数你好”。 我做错了什么?

【问题讨论】:

  • [ "$1" ] && [ "$1" != "--gf" ] 按预期工作,您如何在脚本中调用函数 prepare_for_test
  • @Fravadona 就这样-> prepare_for_test。在结束函数}之后,换行
  • 记住需要将位置参数传递给函数:prepare_for_test "$@"
  • @dan 该死的!这么愚蠢的错误。就是这样!谢谢你们!

标签: bash ubuntu comparison script


【解决方案1】:

比较说法正确:

if [ "$1" = "--gf" ]; then
        startglassfish;
fi

可能还有其他问题,例如:

  1. 确保在调用函数时传递 $1 参数: 写prepare_for_test $1
  2. 问题可能是使用的别名。对于几乎所有用途,别名都被 shell 函数所取代。因此,您要么需要将别名作为函数并将其导出,要么使用特殊变量 BASH_ALIASES。在您的情况下:
if [ "$1" = "--gf" ];then
${BASH_ALIASES[startglassfish]};
fi

【讨论】:

    猜你喜欢
    • 2016-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-04
    • 2012-09-03
    • 2016-07-29
    • 2014-03-22
    相关资源
    最近更新 更多