Bash: echo to the right end of the window (right alignment)

I am looking for success / failure messages that are right-aligned in bash. An example is what apache2 produces when executed: sudo /etc/init.d/apache2 reload , etc.

In the above example, apache2 produces a very nice and concise message [OK] or [fail] that are right-aligned.

In addition, I would like to know how to get the text in red, in case we create a message [fail] .

+8
bash
source share
3 answers
 #!/bin/bash RED=$(tput setaf 1) GREEN=$(tput setaf 2) NORMAL=$(tput sgr0) col=80 # change this to whatever column you want the output to start at if <some condition here>; then printf '%s%*s%s' "$GREEN" $col "[OK]" "$NORMAL" else printf '%s%*s%s' "$RED" $col "[FAIL]" "$NORMAL" fi 
+7
source share

Look at this topic, it may be interesting: how to write a bash script like the ones used in init.d?

On Linux CentOS 6.5 I use the file /etc/init.d/functions:

 #!/bin/bash . /etc/init.d/functions # include the said file action "Description of the action" command exit 0 

Assuming command returns 0 on success, a positive value if an error occurs. To make the script easy to read, I use a function call instead of the whole command.

Here is an example:

 #!/bin/bash . /etc/init.d/functions this_will_fail() { # Do some operations... return 1 } this_will_succeed() { # Do other operations... return 0 } action "This will fail" this_will_fail action "This will succeed" this_will_succeed exit 0 

leads to: console output (note: French ;-))

Hope this helps!

+2
source share

Here is what is mainly based on centos script functions, but more truncated

 #!/bin/bash RES_COL=60 MOVE_TO_COL="printf \\033[${RES_COL}G" DULL=0 BRIGHT=1 FG_BLACK=30 FG_RED=31 FG_GREEN=32 FG_YELLOW=33 FG_BLUE=34 FG_MAGENTA=35 FG_CYAN=36 FG_WHITE=37 ESC="^[[" NORMAL="${ESC}m" RESET="${ESC}${DULL};${FG_WHITE};${BG_NULL}m" BLACK="${ESC}${DULL};${FG_BLACK}m" RED="${ESC}${DULL};${FG_RED}m" GREEN="${ESC}${DULL};${FG_GREEN}m" YELLOW="${ESC}${DULL};${FG_YELLOW}m" BLUE="${ESC}${DULL};${FG_BLUE}m" MAGENTA="${ESC}${DULL};${FG_MAGENTA}m" CYAN="${ESC}${DULL};${FG_CYAN}m" WHITE="${ESC}${DULL};${FG_WHITE}m" SETCOLOR_SUCCESS=$GREEN SETCOLOR_FAILURE=$RED SETCOLOR_NORMAL=$RESET echo_success() { $MOVE_TO_COL printf "[" printf $SETCOLOR_SUCCESS printf $" OK " printf $SETCOLOR_NORMAL printf "]" printf "\r" return 0 } echo_failure() { $MOVE_TO_COL printf "[" printf $SETCOLOR_FAILURE printf $"FAILED" printf $SETCOLOR_NORMAL printf "]" printf "\r" return 1 } action() { local STRING rc STRING=$1 printf "$STRING " shift "$@" && echo_success $"$STRING" || echo_failure $"$STRING" rc=$? echo return $rc } action testing true action testing false 
0
source share

All Articles