开发者

Integer comparison in bash

开发者 https://www.devze.com 2023-02-15 19:45 出处:网络
I need to implement something like: if [ $i -ne $hosts_count - 1] ; then cmd=\"$cmd;\" fi 开发者_C百科But I get

I need to implement something like:

if [ $i -ne $hosts_count - 1] ; then
    cmd="$cmd;"
fi

开发者_C百科But I get

./installer.sh: line 124: [: missing `]'

What I am doing wrong?


The command [ can't handle arithmetics inside its test. Change it to:

if [ $i -ne $((hosts_count-1)) ]; then

Edit: what @cebewee wrote is also true; you must put a space in front of the closing ]. But, just doing that will result in yet another error: extra argument '-'


  1. The ] must be a separate argument to [.
  2. You're assuming you can do math in [.

    if [ $i -ne $(($hosts_count - 1)) ] ; then
    


In bash, you can avoid both [ ] and [[ ]] by using (( )) for purely arithmetic conditions:

if (( i != hosts_count - 1 )); then
  cmd="$cmd"
fi


The closing ] needs to be preceded by a space, i.e. write

if [ $i -ne $hosts_count - 1 ] ; then
    cmd="$cmd;"
fi
0

精彩评论

暂无评论...
验证码 换一张
取 消