简体   繁体   English

bash:从字符串中删除空格

[英]bash: whitespaces removed from string

I've written a small library function to help me exit when the script owner isn't root: 我编写了一个小的库函数来帮助我在脚本所有者不是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 也许取消"%s"而只是

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. 默认情况下,字符串中不对ANSI-C转义序列进行处理-它们与其他文字相同。 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. 但就您而言,由于您只是print提供的格式化字符串,因此您最好将其视为格式化字符串而不是参数。

Or quote the string correctly. 或正确引用字符串。 You can have literal newlines in a quoted string, or use eg the $'string' quoting syntax. 您可以在带引号的字符串中使用文字换行符,也可以使用$'string'引用语法。

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. printf将重新使用格式字符串以提供尽可能多的值字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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