代码如下:
#!/bin/bash
wd1="hello"
wd2="world"
cat >> log.txt <<<"$wd1\t$wd2\n\n"当我运行上面的脚本时,'\t','\n'根本没有展开。所以我把它改成这样:
cat >> log.txt <<<$(echo -e "$wd1\t$wd2\n\n")但是'\t','\n'仍然没有扩展。为什么?
发布于 2012-09-21 18:07:32
来自info bash
3.6.7 Here Strings
------------------
A variant of here documents, the format is:
<<< WORD
The WORD is expanded and supplied to the command on its standard
input.<<<"$wd1\t$wd2\n\n"受到bash扩展的影响,但没有用于\t或\n的标准扩展。这就是为什么它不happen.<<<$(echo -e "$wd1\t$wd2\n\n")不工作,因为它是无引号的。echo会输出特殊字符,但随后会进行字段拆分,并将其替换为空格。你只需要引用它:
cat >> log.txt <<<"$(echo -e "$wd1\t$wd2\n\n")"发布于 2012-09-21 20:30:40
Bash支持另一种类型的引号,它确实扩展了某些转义字符:
word=$'foo\nbar'
echo "$word"不幸的是,这样的带引号的字符串不会进行参数扩展:
word=$'$w1'
echo "$word"如果您使用的是bash 4或更高版本,则可以使用printf设置变量的值:
printf -v word "$wd1\t$wd2\n\n"
cat >> log.txt <<<"$word"发布于 2012-09-21 15:59:29
我更愿意使用(没有此处的字符串):
echo -e "$wd1\t$wd2\n\n" >> log.txthttps://stackoverflow.com/questions/12526364
复制相似问题