【问题标题】:Way to append to file with echo command or other command without using ' ' or " " [duplicate]在不使用“”或“”的情况下使用 echo 命令或其他命令附加到文件的方法 [重复]
【发布时间】:2019-09-08 19:17:48
【问题描述】:

我正在尝试复制整个脚本,而不是脚本输出,而是将整个脚本作为文本行复制到名为 test.sh 的文件中。我正在使用另一个脚本来执行此操作,所以我没有使用 vi 之类的文本编辑器。

我不能使用 echo "" 或 echo '' 因为脚本字符串里面包含双引号和单引号。

我用过但失败的是:

echo "rm disktemp;./xpinfo -i|awk '{print $1}'|grep rhdisk|sed 's!/dev/r!!'>disktemp;for i in $(cat disktemp);do ./xpinfo -i|grep $i|sed 's!/dev/r!!'|awk '{print $6","$1'};done" > test.sh

有什么办法吗?

【问题讨论】:

  • 您的尝试失败了,因为双引号字符串将进行参数扩展,并且$1 等被扩展为空。使用 echo + 单引号可能但很麻烦,您一定要关注 Anubis 的链接
  • 试试 $'' ksh93 有(也可能是 bash)这个特性,所以可以嵌套引用。

标签: bash shell unix ksh


【解决方案1】:

扩展引用

$'' $""

echo $'rm disktemp;./xpinfo -i|awk \'{print $1}\'|grep rhdisk|sed \'s!/dev/r!!\'>disktemp;for i in $(cat disktemp);do ./xpinfo -i|grep $i|sed \'s!/dev/r!!\'|awk \'{print $6","$1\'};done'

输出:

rm disktemp;./xpinfo -i|awk '{print $1}'|grep rhdisk|sed 's!/dev/r!!'>disktemp;for i in $(cat disktemp);do ./xpinfo -i|grep $i|sed 's!/dev/r!!'|awk '{print $6","$1'};done

不幸的是,您需要使用 \ 转义每个引号,以将它们保留在输出中。最好全部转义,但正如您在下面看到的那样,仅用于 $'' 或 $"" 的那个就足够了:

echo $'This is a text \'single\' and "double" quote in it.'
This is a text 'single' and "double" quote in it.

echo $"This is a text 'single' and \"double\" quote in it."
This is a text 'single' and "double" quote in it.

echo $'This is a text \'single\' and \"double\" quote in it.'
This is a text 'single' and "double" quote in it.

【讨论】:

  • 谢谢你,这正是我想做的。
【解决方案2】:

我认为上面的答案涵盖了您想要做的事情,但我仍然对您的要求感到有些困惑。如果您要添加到脚本中的代码是静态的(看起来就是这样),您是否可以不将其写入文件一次并执行以下操作:

cat common-code > test.sh

在您的脚本中?

【讨论】:

    猜你喜欢
    • 2017-03-14
    • 1970-01-01
    • 2013-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-14
    相关资源
    最近更新 更多