我已经编写了一个小的库函数来帮助我在脚本所有者不是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.如何才能使换行符正确显示?
发布于 2011-08-30 17:35:43
也许可以去掉"%s"然后
printf "$1"在这种情况下是最简单的。
默认情况下,ANSI-C转义序列在字符串中不会被视为ANSI-C转义序列-它们与其他文字相同。表单
$'ANSI text here'将进行反斜杠-转义替换。()
在您的例子中,由于您只是对提供的格式化字符串执行print操作,因此可以将其视为格式化字符串而不是参数。
发布于 2011-08-30 17:35:22
只需使用echo -e而不是printf
发布于 2011-08-30 17:38:22
或者正确地引用字符串。您可以在带引号的字符串中使用文字换行符,也可以使用$'string' quoting语法。
https://stackoverflow.com/questions/7241175
复制相似问题