Skip to content
Advertisement

advanced printf explanation in bash

I just found this programming segment in my son’s Bash file. I am quite a newbie and unable to understand the printf syntax. Can someone explain me the COMMENTED printf in the segment below??

#printf "33[1;34m"
while [ -d /proc/$PROC ]; do
    printf '33[s33[u[/] %s33[u' "$str"; sleep "$delay"
    printf '33[s33[u[—] %s33[u' "$str"; sleep "$delay"
    printf '33[s33[u[] %s33[u' "$str"; sleep "$delay"
    printf '33[s33[u[|] %s33[u' "$str"; sleep "$delay"
done
#printf '33[s33[u%*s33[u33[0m' $((${#str}+6)) " "  # return to normal(It disappears.)

Advertisement

Answer

It’s is nothing but a busy/wait spinner and the lines commented do nothing but set a blue foreground color and the last erases the line the spinner and text. 33 is just character 27 which is part of the ANSI escape followed by [. See here Spinner Animation and echo command The ‘s’ saves the cursor position and the ‘u’ restores the cursor position to where it was last saved — your fine, nothing nefarious… (I’m fairly sure that is exactly where that code came from)

In more detail:

#printf "33[1;34m"   /* simply sets a blue foreground color */

Then the final:

#printf '33[s33[u%*s33[u33[0m' $((${#str}+6)) " "
  1. 33[s save cursor position,

  2. 33[u restore to last saved,

  3. '%*s' normal printf format specifier for a string with the * to note the field width will be specified by the 1st argument,

  4. 33[u restore to last saved position,

  5. 33[0m return the color to default.

The first argument is $((${#str}+6)) the length of the string your printing plus 6-chars for the spinner, e.g. '[ ] ' and the the 2nd argument, a space (e.g. " ") for the actual string to overwrite the line with empty-spaces.

It simply erases the line used with the spinner in it.

By commenting the lines, the color is left at the default (the 1st comment) and the final line with the string and the last spinner position is left on screen (2nd commented printf)

Here is an ANSI Escape sequences reference that explains the escapes further…

Advertisement