Cocoa Puffs Cocoa Puffs - 9 months ago 33
Linux Question

bash how subtract characters from string

I've been trying to get a string to output each character individually on the same line (with a fancy gradient effect in bash), although something in the subscripting part isn't working out quite right:

n=0 ; for i in {16..21} {21..16} ; do
echo -ne "\033[48;5;${i}m ${str:str[i-n]:n++} \033[0m" ;
sleep 1;

It outputs:

f fo foo foob fooba foobar foobar foobar foobar foobar foobar

but I'm hoping to get:

f o o b a r

so it might be my approach is off kilter, or I'm missing something obvious?


In the expression ${str:str[i-n]:n++}, the numeric value of str[i-n] is effectively 0. The partially calculated values in the loop steps look something like this:

  • ${str:0:1}
  • ${str:0:2}
  • ${str:0:3}
  • ${str:0:4}
  • ... and so on

The value after the second : inside ${var:start:count} is the number of characters to count from the start position. As the start position never changes, you get f, fo, foo, foob, and so on.

If you want to get f, o, o, b, a, r, then you would need to advance the start position, and keep the count at 1, using this expression: