I’ve written a small library function to help me exit when the script owner isn’t root:
#!/bin/bash
# Exit for non-root user
exit_if_not_root() {
if [ "$(id -u)" == "0" ]; then return; fi
if [ -n "$1" ];
then
printf "%s" "$1"
else
printf "Only root should execute This script. Exiting now.\n"
fi
exit 1
}
Here I call it from another file:
#!/bin/bash
source ../bashgimp.sh
exit_if_not_root "I strike quickly, being moved. But thou art not quickly moved to strike.\n You're not root, exiting with custom message."
And the output is:
I strike quickly, being moved. But thou art not quickly moved to strike.\n You're not root, exiting with custom message.
How can I get the newline to appear correctly?
Maybe do away with the
"%s"and justwould be simplest in this case.
ANSI-C escape sequences are not treated as such by default in strings – they are the same as other literals. The form
will undergo backslash-escape replacement though. (Ref.)
In your case though, as you’re just
printing the formatted string provided, you may as well treat it as the format string rather than an argument.