Shell 通过替换 PAM 文件中的文本来更改密码策略的脚本

Shell script to change password policy by replacing text in PAM files

我正在编写一个 shell 脚本,它将使用 Ubuntu 14.04 中的 PAM 文件完全更改密码策略。我这样做的方式是

sudo sh -c 'echo "I want to change this text" >/etc/pam.d/example.txt'

我 运行 遇到的问题是我无法创建新行。我对此进行了研究,有人说 HTML 标签 <br> 有效,但我试过

sudo sh -c 'echo "I want to change this text. <br> This should be a new line." >/etc/pam.d/example.txt 

(和)

sudo sh -c 'echo "I want to change this text. <br /> This should be a new line." >/etc/pam.d/example.txt'

但它只是在文本文件上打印 <br><br /> 标签。我该如何解决这个问题?

使用 echo 中的 -e 标志启用 back-slashed 转义序列(在 echo 上,作为 GNU coreutils 的一部分),

sudo sh -c 'echo -e "I want to change this text\nThis should be a new line" '
I want to change this text
This should be a new line

对于你的情况,应该是,

sudo sh -c 'echo -e "I want to change this text\nThis should be a new line" > /etc/pam.d/example.txt'

POSIX echo 语句中你可以直接嵌入 \n 个字符而不用 -e 标志,

sudo sh -c 'echo "I want to change this text\nThis should be a new line" > /etc/pam.d/example.txt' 

基本上,您应该停止使用 echo 来编写任何新内容。

虽然 POSIX 描述了 echo 的行为,但在实践中它并没有达到应有的可移植性。 POSIX echo even recommends that "New applications are encouraged to use printf 的文档而不是 echo。"

您还可以找到对此 here on the S.E. network. And the bash hackers' wiki touches on this too. And it's mentioned in one of the bash pitfalls 的引用。

sudo sh -c 'printf "First line.\nSecond line.\n" >/etc/pam.d/example.txt'