Bash printf%q无效指令 [英] Bash printf %q invalid directive

查看:102
本文介绍了Bash printf%q无效指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在.bashrc文件中更改我的PS1. 我找到了一个使用printf和%q指令来转义字符的脚本:

I want to change my PS1 in my .bashrc file. I've found a script using printf with %q directive to escape characters :

#!/bin/bash
STR=$(printf "%q" "PS1=\u@\h:\w\$ ")
sed -i '/PS1/c\'"$STR" ~/.bashrc

问题是我收到此错误:

script.sh: 2: printf: %q: invalid directive

有什么主意吗?也许是逃脱角色的另一种方法?

Any idea ? Maybe an other way to escape the characters ?

推荐答案

printf命令内置在bash中.这也是一个外部命令,通常安装在/usr/bin/printf中.在大多数Linux系统上,/usr/bin/printf是GNU coreutils实现.

The printf command is built into bash. It's also an external command, typically installed in /usr/bin/printf. On most Linux systems, /usr/bin/printf is the GNU coreutils implementation.

GNU coreutils printf命令的较早版本不支持%q格式说明符;它是在2016年10月20日发布的8.25版中引入的. bash的内置printf命令可以-并且只要bash具有内置的printf命令即可.

Older releases of the GNU coreutils printf command do not support the %q format specifier; it was introduced in version 8.25, released 2016-10-20. bash's built-in printf command does -- and has as long as bash has had a built-in printf command.

该错误消息表示您正在使用bash以外的其他软件运行script.sh.

The error message implies that you're running script.sh using something other than bash.

由于#!/bin/bash行似乎正确,因此您可能正在执行以下操作之一:

Since the #!/bin/bash line appears to be correct, you're probably doing one of the following:

sh script.sh
. script.sh
source script.sh

相反,只需直接执行它(确保它具有执行权限后,如果需要,使用chmod +x):

Instead, just execute it directly (after making sure it has execute permission, using chmod +x if needed):

./script.sh

或者您也可以手动编辑.bashrc文件.如果执行正确,该脚本会将此行添加到您的.bashrc:

Or you could just edit your .bashrc file manually. The script, if executed correctly, will add this line to your .bashrc:

PS1=\\u@\\h:\\w\$\ 

(该行末尾的空格很大.)或者您可以像这样更简单地做到这一点:

(The space at the end of that line is significant.) Or you can do it more simply like this:

PS1='\u@\h:\w\$ '

该脚本的一个问题是它将替换提及PS1的每行 .如果只设置一次,否则不引用它,那很好,但是如果您有类似的东西:

One problem with the script is that it will replace every line that mentions PS1. If you just set it once and otherwise don't refer to it, that's fine, but if you have something like:

if [ ... ] ; then
    PS1=this
else
    PS1=that
fi

然后脚本将彻底弄乱它.太聪明了.

then the script will thoroughly mess that up. It's just a bit too clever.

这篇关于Bash printf%q无效指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆