简体   繁体   English

bash中变量不等式的正确语法是什么?

[英]What's the correct syntax for variable inequalities in bash?

I'm a bit new to bash so please excuse any naive questions or nooby stuff I do. 我对bash有点陌生,所以请原谅我任何幼稚的问题或nooby的事情。

So I wrote a quick script that lists all tput colors, and it works pretty well. 所以我写了一个快速的脚本,列出了所有色带的颜色,并且效果很好。 It looks like this: 看起来像这样:

unset x; for i in {1..256}; do tput setab $x; echo $x; x=$((x+1)); done

But I wanted to use less than/equal to instead of what I did above. 但是我想使用小于/等于来代替上面的操作。 I tried doing a bunch of stuff like this: 我尝试做很多这样的事情:

unset x; if [ $x -le 256] ; do tput setab $x ; echo $x ; x=$((x+1)) ; done

And this: 和这个:

unset x; if [ $x -le 256] then do tput setab $x ; echo $x ; x=$((x+1)) ; done

But I can't get the syntax right, it just says unexpected token "done" or "do". 但是我无法正确理解语法,它只是说意外的标记“完成”或“执行”。 Google didn't help me, nor did I find anything that answered my questions here on Stack Overflow. Google并没有帮助我,也没有在Stack Overflow上找到任何可以回答我的问题的东西。 Also I'd like to be able to have it unset x after it reaches 256 and then keep repeating the script so it could look trippy. 另外,我希望能够在达到256后将其取消设置为x,然后继续重复执行脚本,以便使其看起来像是迷幻的。 So yeah, if anyone could help I'd appreciate it, thanks. 是的,如果有人可以帮助我,我会很感激,谢谢。

An if block cannot be the condition for a do loop. if块不能成为do循环的条件。 Use while instead. 改为使用while Also, when you unset x , $x will be undefined and cannot be compared to a number. 另外,当您unset x$x将是未定义的并且不能与数字进行比较。 I suppose you actually want something like this: 我想您实际上想要这样的东西:

unset x
x=1
while [ $x -le 256 ]; do
  tput setab $x
  echo $x
  x=$((x+1))
done

The last expression ( x=$((x+1)) ) could be simplified to ((x++)) . 最后一个表达式( x=$((x+1)) )可以简化为((x++)) And, as Uwe pointed out, there must be whitespace before and after square brackets (except between a closing square bracket and a semicolon), otherwise bash won't be able to parse the statement correctly. 而且,正如Uwe指出的那样,方括号之前和之后都必须有空格(封闭的方括号和分号之间除外),否则bash将无法正确解析该语句。

However, if you just increment $x with every cycle of the loop, this approach has no advantage whatsoever over a for loop: 但是,如果仅在循环的每个循环中增加$x ,则此方法与for循环相比没有任何优势:

for x in {1..256}; do
  tput setab $x
  echo $x
done

Only for completeness, you can write your 1st example as: 仅出于完整性考虑,您可以将第一个示例编写为:

for i in {1..256}
do
        tput setab $i
        echo $i
done

So, you can use directly the $i and don't need use/increment the $x . 因此,您可以直接使用$i ,而无需使用/增加$x

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM