1

What is the easiest way to quote bash command arguments that contain single quotes and double quotes without variable interpolation?

In Ruby you can quote strings using %{}, %[] etc. In that case single quotes and double quotes will be treated as characters.

My question was not really complete here is further explanation:

The reason I am asking that is because I often run ruby and perl code at the command line. Since those languages are using extensively single quotes and double quotes and global variables like $1 $_ etc. I get conflicts with bash.

example:

ls -lat | ruby -p -e '$_ =~ /(\S+)\s+(\S+)\s+(\S+)/; $_ = "'\''" + ($3 || "") + "'\''" + "\n"'

I was looking for something similar to the % quoting in ruby:

ls -lat | ruby -p -e %{$_ =~ /(\S+)\s+(\S+)\s+(\S+)/; $_ = "'" + ($3 || "") + "'" + "\n"}
4

2 回答 2

5

使用heredoc可能最简单:

read -r arg << \EOF
A string "with" 'quotes'
EOF

将 $arg 设置为 heredoc 的未插值内容。这不允许在变量中嵌入换行符。如果你想要一个多行值:

unset var; while read -r v; do var="$var${var+
}$v; done << \EOF
A multi-line "" string
with different 'quotes'
EOF

不幸的是,Ormaaj 使用 IFS 的评论无法捕获换行符。

于 2012-10-10T02:57:47.300 回答
1

由于您不需要变量插值,因此可以使用$'...'引号(尽管您仍然需要转义单引号,因此这可能不符合您的要求):

x=$'String containing \' and "'
于 2012-10-10T03:11:03.847 回答