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.
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