2

I'm a bit new to bash so please excuse any naive questions or nooby stuff I do.

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. 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. So yeah, if anyone could help I'd appreciate it, thanks.

AwesomeBen1
  • 75
  • 10

2 Answers2

3

An if block cannot be the condition for a do loop. Use while instead. Also, when you unset x, $x will be undefined and cannot be compared to a number. 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++)). 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.

However, if you just increment $x with every cycle of the loop, this approach has no advantage whatsoever over a for loop:

for x in {1..256}; do
  tput setab $x
  echo $x
done
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • 3
    By the way, note that there are spaces around `[` and `]`. These are mandatory (except for the space between `]` and `;`, which is optional). – Uwe May 27 '13 at 17:58
  • Thanks for your help! I decided to use the for loop you included, as it's (obviously) better than what I had. I also feel proud of myself for making a bit of a messy solution for a repeating tput rainbow using your solution. – AwesomeBen1 May 28 '13 at 01:14
1

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.

clt60
  • 62,119
  • 17
  • 107
  • 194