bad-op.sh

来自「Shall高级编程」· Shell 代码 · 共 47 行

SH
47
字号
#!/bin/bash# bad-op.sh: Trying to use a string comparison on integers.echonumber=1# The following "while loop" has two errors:#+ one blatant, and the other subtle.while [ "$number" < 5 ]    # Wrong! Should be:  while [ "$number" -lt 5 ]do  echo -n "$number "  let "number += 1"done  #  Attempt to run this bombs with the error message:#+ bad-op.sh: line 10: 5: No such file or directory#  Within single brackets, "<" must be escaped,#+ and even then, it's still wrong for comparing integers.echo "---------------------"while [ "$number" \< 5 ]    #  1 2 3 4do                          #  echo -n "$number "        #  This *seems to work, but . . .  let "number += 1"         #+ it  actually does an ASCII comparison,done                        #+ rather than a numerical one.echo; echo "---------------------"# This can cause problems. For example:lesser=5greater=105if [ "$greater" \< "$lesser" ]then  echo "$greater is less than $lesser"fi                          # 105 is less than 5#  In fact, "105" actually is less than "5"#+ in a string comparison (ASCII sort order).echoexit 0

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?