简体   繁体   中英

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 "\033[1;34m"
while [ -d /proc/$PROC ]; do
    printf '\033[s\033[u[/] %s\033[u' "$str"; sleep "$delay"
    printf '\033[s\033[u[—] %s\033[u' "$str"; sleep "$delay"
    printf '\033[s\033[u[\] %s\033[u' "$str"; sleep "$delay"
    printf '\033[s\033[u[|] %s\033[u' "$str"; sleep "$delay"
done
#printf '\033[s\033[u%*s\033[u\033[0m' $((${#str}+6)) " "  # return to normal(It disappears.)

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. \\033 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 "\033[1;34m"   /* simply sets a blue foreground color */

Then the final:

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

  2. \\033[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. \\033[u restore to last saved position,

  5. \\033[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, eg '[ \\ ] ' and the the 2nd argument, a space (eg " " ) 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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM