简体   繁体   中英

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-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?

只需使用echo -e而不是printf

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 print ing the formatted string provided, you may as well treat it as the format string rather than an argument.

Or quote the string correctly. You can have literal newlines in a quoted string, or use eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM