【问题标题】:bash: whitespaces removed from stringbash:从字符串中删除空格
【发布时间】:2011-08-30 09:30:03
【问题描述】:

我编写了一个小型库函数来帮助我在脚本所有者不是 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.

如何让换行符正确显示?

【问题讨论】:

    标签: string bash newline


    【解决方案1】:

    也许可以取消 "%s" 而只是

    printf "$1"
    

    在这种情况下是最简单的。

    默认情况下,ANSI-C 转义序列在字符串中不被视为 - 它们与其他文字相同。表格

    $'ANSI text here'
    

    将进行反斜杠转义替换。 (Ref.)

    但在您的情况下,由于您只是 printing 提供的格式化字符串,您不妨将其视为格式字符串而不是参数。

    【讨论】:

    • 谢谢,这行得通。但为什么它一开始就不起作用?
    【解决方案2】:

    只需使用echo -e 而不是printf

    【讨论】:

      【解决方案3】:

      或者正确引用字符串。您可以在带引号的字符串中使用文字换行符,或使用例如$'string' 引用语法。

      【讨论】:

        【解决方案4】:

        在函数中,将行改为

        printf "%s\n" "$@"
        

        然后像这样调用函数

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

        printf 将为您提供的尽可能多的值字符串重复使用格式字符串。

        【讨论】:

          猜你喜欢
          • 2011-09-21
          • 2017-11-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多