【问题标题】:When/how to use "==" or "-eq" operator in test?何时/如何在测试中使用“==”或“-eq”运算符?
【发布时间】:2014-09-12 18:06:26
【问题描述】:

在下面的代码中,我想将命令行参数与参数进行比较,但我不确定将参数与参数进行比较的当前语法是什么......即“==”或“-eq”。

#!/bin/bash
argLength=$#
#echo "arg = $1"

if [ argLength==0 ]; then
#Running for the very first
#Get the connected device ids and save it in  an array
  N=0
  CONNECTED_DEVICES=$(adb devices | grep -o '\b[A-Za-z0-9]\{8,\}\b'|sed -n '2,$p')
  NO_OF_DEVICES=$(echo "$CONNECTED_DEVICES" | wc -l)
  for CONNECTED_DEVICE in $CONNECTED_DEVICES ; do
       DEVICE_IDS[$N]="$CONNECTED_DEVICE"
       echo "DEVICE_IDS[$N]= $CONNECTED_DEVICE"
       let "N= $N + 1"
  done
  for SEND_DEVICE_ID in ${DEVICE_IDS[@]} ; do
      callCloneBuildInstall $SEND_DEVICE_ID
  done
elif [ "$1" -eq -b ]; then
  if [ $5 -eq pass ]; then 
      DEVICE_ID=$3
      ./MonkeyTests.sh -d $DEVICE_ID
  else
    sleep 1h
    callCloneBuildInstall $SEND_DEVICE_ID
  fi
elif [ "$1" -eq -m ]; then 
  echo "Check for CloneBuildInstall"
  if [ "$5" -eq pass ]; then 
      DEVICE_ID=$3
      callCloneBuildInstall $SEND_DEVICE_ID
  else
    echo "call CloneBuildInstall"
    # Zip log file and save it with deviceId
    callCloneBuildInstall $SEND_DEVICE_ID
  fi
fi

function callCloneBuildInstall {
  ./CloneBuildInstall.sh -d $SEND_DEVICE_ID
}

【问题讨论】:

  • @user2864740 比较是真的.. 我的意思是当我写 "$1" -eq -m 或者它应该是 $1 -eq -m?
  • 实际上,在使用 Bash 时,更喜欢 == 而不是 =
  • @konsolebox 为什么更喜欢==?它们在 bash 中是等价的,当您编写可移植(非 bash 依赖)脚本时,习惯使用 == 会让您感到困惑。
  • @GordonDavisson 如果我们不关心可移植性,== 更具可读性。

标签: linux bash shell syntax


【解决方案1】:

何时/如何在测试中使用“==”或“-eq”运算符?

简单地说,在进行词法比较(即字符串比较)时使用==,但在进行数值比较时使用-eq

-eq(等于)的其他形式有-ne(不等于)、-gt(大于)、-ge(大于或等于)、-lt(小于)和@987654328 @(小于或等于)。

有些人可能还建议首选(( ))

例子:

[[ $string == "something else" ]]
[[ $string != "something else" ]] # (negated)
[[ $num -eq 1 ]]
[[ $num -ge 2 ]]
(( $num == 1 ))
(( $num >= 1 ))

并且在使用 Bash 时始终使用 [[ ]] 而不是 [ ],因为前者会跳过与分词和路径名扩展等条件表达式无关的不必要扩展。

【讨论】:

    【解决方案2】:

    来自help test

    [...]

      STRING1 = STRING2
                     True if the strings are equal.
    

    [...]

      arg1 OP arg2   Arithmetic tests.  OP is one of -eq, -ne,
                     -lt, -le, -gt, or -ge.
    

    但无论如何,条件的每个部分都是[ 的单独参数。

    if [ "$arg" -eq 0 ]; then
    
    if [ "$arg" = 0 ]; then
    

    【讨论】:

      【解决方案3】:

      为什么不使用类似的东西

      如果 [ "$#" -ne 0 ];那么 # args 的数量不应为零
      回声“用法:”

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-01
        • 2016-06-30
        • 2019-01-07
        • 2020-07-11
        • 1970-01-01
        • 2013-12-25
        • 2023-01-24
        • 2011-05-30
        相关资源
        最近更新 更多