Padding characters in printf

前端 未结 13 825
半阙折子戏
半阙折子戏 2020-11-30 16:58

I am writing a bash shell script to display if a process is running or not.

So far, I got this:

printf \"%-50s %s\\n\" $PROC_NAME [UP]
13条回答
  •  一向
    一向 (楼主)
    2020-11-30 17:32

    Bash + seq to allow parameter expansion

    Similar to @Dennis Williamson answer, but if seq is available, the length of the pad string need not be hardcoded. The following code allows for passing a variable to the script as a positional parameter:

    COLUMNS="${COLUMNS:=80}"
    padlength="${1:-$COLUMNS}"
    pad=$(printf '\x2D%.0s' $(seq "$padlength") )
    
    string2='bbbbbbb'
    for string1 in a aa aaaa aaaaaaaa
    do
         printf '%s' "$string1"
         printf '%*.*s' 0 $(("$padlength" - "${#string1}" - "${#string2}" )) "$pad"
         printf '%s\n' "$string2"
         string2=${string2:1}
    done
    

    The ASCII code "2D" is used instead of the character "-" to avoid the shell interpreting it as a command flag. Another option is "3D" to use "=".

    In absence of any padlength passed as an argument, the code above defaults to the 80 character standard terminal width.

    To take advantage of the the bash shell variable COLUMNS (i.e., the width of the current terminal), the environment variable would need to be available to the script. One way is to source all the environment variables by executing the script preceded by . ("dot" command), like this:

    . /path/to/script
    

    or (better) explicitly pass the COLUMNS variable when executing, like this:

    /path/to/script $COLUMNS
    

提交回复
热议问题