Atomiklan
Atomiklan

Reputation: 5434

Bash output to same line while preserving column

Ok, this is going to seem like a basic question at first, but please hear me out. It's more complex than the title makes it seem!

Here is the goal of what I am trying to do. I would like to output to console similar to Linux boot.

Operating system is doing something...                                                 [ OK ]

Now this would seem to be obvious... Just use printf and set columns. Here is the first problem. The console needs to first print the action

Operating system is doing something...

Then it needs to actually do the work and then continue by outputting to the same line with the [ OK ].

This would again seem easy to do using printf. Simply do the work (in this case, call a function) and return a conditional check and then finish running the printf to output either [ OK ] or [ FAIL ]. This technically works, but I ran into LOTS of complications doing this. This is because the function must be called inside a subshell and I cant pass certain variables that I need. So printf is out.

How about just using echo -n? That should work right? Echo the first part, run the function, then continue echoing based on the return to the same line. The problem with this solution is I can no longer preserve the column formatting that I can with printf.

Operating system is doing something...                                             [ OK ]
Operating system is doing something else...                                             [ OK ]
Short example...                                             [ OK ]

Any suggestions how I can fix any of these problems to get a working solution? Thanks

Here is another way I tried with printf. This gives the illusion of working, but the method is actually flawed because it does not give you the progress indication, ie the function runs first before it ever prints out the the function is running. The "hey im doing stuff" prints immediately with the "hey im done" message. As a result, its pointless.

VALIDATE $HOST; printf "%-50s %10s\n" " Validating and sanitizing input..." "$(if [ -z "$ERROR" ]; then echo "[$GREEN   OK   $RESET]"; else echo "[$RED  FAIL  $RESET] - $ERROR"; echo; exit; fi)"

Upvotes: 0

Views: 321

Answers (1)

jhnc
jhnc

Reputation: 16662

There's no particular reason all the printf strings have to be printed together, unless you're worried some code you call is going to move the cursor.

Reordering your example:

printf "%-50s " " Validating and sanitizing input..."

VALIDATE $HOST

if [ -z "$ERROR" ]; then
    printf "%10s\n" "[$GREEN   OK   $RESET]";
else
    printf "%10s\n" "[$RED  FAIL  $RESET] - $ERROR"
    echo
    exit
fi

I have no idea what $ERROR contains or where it is supposed to display.

Upvotes: 1

Related Questions