使用Bash时需要转义哪些字符? [英] Which characters need to be escaped when using Bash?

查看:345
本文介绍了使用Bash时需要转义哪些字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Bash中是否有需要转义的字符的完整列表?可以仅使用sed进行检查吗?

Is there any comprehensive list of characters that need to be escaped in Bash? Can it be checked just with sed?

尤其是,我正在检查是否需要转义%.我尝试过

In particular, I was checking whether % needs to be escaped or not. I tried

echo "h%h" | sed 's/%/i/g'

并且工作正常,没有转义%.这是否意味着%不需要转义?这是检查必要性的好方法吗?

and worked fine, without escaping %. Does it mean % does not need to be escaped? Was this a good way to check the necessity?

更笼统:它们是在shellbash中要转义的相同字符吗?

And more general: are they the same characters to escape in shell and bash?

推荐答案

有两个简单而安全的规则,它们不仅在sh中起作用,而且在bash中也起作用.

There are two easy and safe rules which work not only in sh but also bash.

这适用于除单引号本身以外的所有字符.要转义单引号,请在其前关闭引号,插入单引号,然后重新打开引号.

This works for all chars except single quote itself. To escape the single quote, close the quoting before it, insert the single quote, and re-open the quoting.

'I'\''m a s@fe $tring which ends in newline
'

sed命令:sed -e "s/'/'\\\\''/g; 1s/^/'/; \$s/\$/'/"

这适用于除换行符以外的所有字符.对于换行符,请使用单引号或双引号. 仍然必须处理空字符串-替换为""

This works for all characters except newline. For newline characters use single or double quotes. Empty strings must still be handled - replace with ""

\I\'\m\ \a\ \s\@\f\e\ \$\t\r\i\n\g\ \w\h\i\c\h\ \e\n\d\s\ \i\n\ \n\e\w\l\i\n\e"
"

sed命令:sed -e 's/./\\&/g; 1{$s/^$/""/}; 1!s/^/"/; $!s/$/"/'.

其中有一组容易安全的字符,例如[a-zA-Z0-9,._+:@%/-],可以不转义以使其更具可读性

There's an easy safe set of characters, like [a-zA-Z0-9,._+:@%/-], which can be left unescaped to keep it more readable

I\'m\ a\ s@fe\ \$tring\ which\ ends\ in\ newline"
"

sed命令:LC_ALL=C sed -e 's/[^a-zA-Z0-9,._+@%/-]/\\&/g; 1{$s/^$/""/}; 1!s/^/"/; $!s/$/"/'.

请注意,在sed程序中,无法知道输入的最后一行是否以换行符结尾(除非为空).这就是上述两个sed命令都假定不这样做的原因.您可以手动添加带引号的换行符.

Note that in a sed program, one can't know whether the last line of input ends with a newline byte (except when it's empty). That's why both above sed commands assume it does not. You can add a quoted newline manually.

请注意,仅在POSIX意义上为文本定义了shell变量.未定义处理二进制数据.对于重要的实现,二进制可以使用NUL字节(因为变量是使用C字符串实现的,并且打算用作C字符串,即程序参数),但是您应该切换到二进制"语言环境,例如latin1

Note that shell variables are only defined for text in the POSIX sense. Processing binary data is not defined. For the implementations that matter, binary works with the exception of NUL bytes (because variables are implemented with C strings, and meant to be used as C strings, namely program arguments), but you should switch to a "binary" locale such as latin1.

(您可以通过阅读sh的POSIX规范轻松验证规则.对于bash,请参阅@AustinPhillips链接的参考手册)

(You can easily validate the rules by reading the POSIX spec for sh. For bash, check the reference manual linked by @AustinPhillips)

这篇关于使用Bash时需要转义哪些字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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