例如,如果我的目标是运行像这样的一行bash命令,
sudo bash -c ' sudo bash -c '' sudo bash -c ''' echo ''''1234'''' ''' '' '
它不工作
我也尝试了第二个命令
sudo bash -c ' sudo bash -c " sudo bash -c ''' echo ""1234"" ''' " '
也不行
sudo bash -c ' sudo bash -c " echo '''123''' " '
第三个,它确实有效,但它在顶部只有3个级别。
那么,是否有一种实际的方法可以让这个命令只使用引号的技巧?
如何处理一行bash命令中的多个引号?
使用函数,declare -f
和printf "%q"
来正确引用内容。不要自己做。
# Function to run, just normally write stuff to execute.
work() {
echo "1234"
}
# Script to run - contains work function definition and calls work.
script="$(declare -f work); work"
# bash -c "$script"
# quote it
script2="$(printf " %q" bash -c "$script")"
# bash -c "$script2"
# Well, no point, but an example, quote it again:
script3="$(printf " %q" bash -c "$script2")"
bash -c "$script3"
printf "%q " bash -c "$script3"
输出:
1234
bash -c bash -c \ bash\ -c\ \$\'work\ \(\)\ \\n\{\ \\n\ \ \ \ echo\ \"1234\"\\n\}\;\ work\'
您可以将bash -c ....
行复制到您的终端并执行它。
如果你想要不同的引用风格,你可以使用bash特殊的${var@Q}
变量扩展或/bin/printf
可执行文件从coretils
是否有一种实际的方法可以让这个命令只使用引号的技巧?
。引号按段分组,写多个引号是无用的,用于可读性。在您的示例中,'bash -c ''''1234'''''
只是'qouted stuff'unqouted stuff'quoted stuff'unqouted stuff' etc..
。做''''
改变不了什么。您必须转义'
引号以保留它们的字面意义。