开发者

bash: whitespaces removed from string

I've written a small library function to help me exit when the script owner isn't root:

#!/bin/bash   

# Exit for non-ro开发者_运维技巧ot 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 just

printf "$1"

would 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

$'ANSI text here'

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.


Just use echo -e instead of printf


Or quote the string correctly. You can have literal newlines in a quoted string, or use e.g. the $'string' quoting syntax.


In the function, change the line to

printf "%s\n" "$@"

And call the function like this

exit_if_not_root "text for line 1" "text for line2" "text for line 3"

printf will re-use the format string for as many value strings as you supply.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜