bash:从字符串中删除空格
我编写了一个小库函数来帮助我在脚本所有者不是 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
}
这里我从另一个文件中调用它:
#!/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."
输出是:
I strike quickly, being moved. But thou art not quickly moved to strike.\n You're not root, exiting with custom message.
如何让换行符正确显示?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
也许去掉
"%s"
在这种情况下是最简单的。
默认情况下,字符串中的 ANSI-C 转义序列不会被视为这样 - 它们与其他文字相同。 不过,该表单
将进行反斜杠转义替换。 (参考。)
在您的但在这种情况下,由于您只是
打印
提供的格式化字符串,因此您也可以将其视为格式字符串而不是参数。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
print
ing the formatted string provided, you may as well treat it as the format string rather than an argument.只需使用
echo -e
而不是printf
Just use
echo -e
instead ofprintf
或者正确引用字符串。您可以在带引号的字符串中包含文字换行符,或者使用例如
$'string'
引用语法。Or quote the string correctly. You can have literal newlines in a quoted string, or use e.g. the
$'string'
quoting syntax.在函数中,将行更改为
And call the function like this
printf
将为您提供的尽可能多的值字符串重复使用格式字符串。In the function, change the line to
And call the function like this
printf
will re-use the format string for as many value strings as you supply.