I have a slight aesthetic problem that I can't seem to wrap my mind around, and I was hoping I might get some input on it here.
Basically, I want to be able to print a status message, execute a command, and then follow it with a message about it succeeding on the same line. That is easy enough to do, I just have something like this:
Code:
echo -n "Running command..."
command 2>/dev/null
echo "Done!"
That works fine, but the problem comes in when the task fails. In my Bash scripts I use an error handler, so it actually looks like this:
Code:
ErrorMsg ()
{
# ErrorMsg <Error Type> <Error Message>
# Displays either a minor (warning) or critical error, exiting on an critical.
if [ "$1" == "ERR" ]; then
# This is a critical error, game over.
echo " ERROR: $2"
exit 1
elif [ "$1" == "WRN" ]; then
# This is only a warning, script continues but may not work fully.
echo " WARNING: $2"
fi
}
echo -n "Running command..."
command 2>/dev/null || ErrorMsg ERR "The command has failed!"
echo "Done!"
Functionally, this works. But the problem is that since I printed the first line "Running command..." without the newline, my error message follows it instead of being below and to the right as I want.
So it looks like:
Code:
Running command... ERROR: The command has failed!
Instead of:
Code:
Running command...
ERROR: The command has failed!
Now, the obvious solution was to change my echo lines in ErrorMsg () to:
Code:
echo -e "\n ERROR: $2"
BUT, here is the problem. I also want to call ErrorMsg in situations where I have not previously printed a line without a newline, in which case, using this method makes the error print a blank line first.
So basically, my problem is that I want to be able to print the error line where I want it, in either situation. It seems that I need some method of detecting if the previous line was ended or not, and then act accordingly.
My other idea was to give the newline command to ErrorMsg, so it would look like:
Code:
ErrorMsg ERR "\nThis is an error."
But because of the way I am handling it, this won't work properly since the "ERROR:" part is always printed regardless of the line I give it to print.
So it comes out like:
Code:
ERROR:
This is an error.
Terrible.
I was thinking that I could do something where I check if the first characters of the string are "\n", then strip them adjust the echo command accordingly? Like:
Code:
if $string starts with \n; then
strip \n from $string
echo -e "\n ERROR: $string"
else
echo " ERROR: $string"
fi
Is there a better way to handle this issue? I don't actually know how to strip the characters from the string and such, but I am sure it can't be too difficult. I just want to know if there is a better method to work this out before I start playing around with my own concept.
P.S.
Yes, I am aware this is a rather ridiculous question in the grand scheme of things, but I am a bit obsessive and it bothers me that my error message don't all look the same with the current method.