Bash 壳膨胀法
如何在herdoc for all命令中进行子shell扩展 例如:Bash 壳膨胀法,bash,Bash,如何在herdoc for all命令中进行子shell扩展 例如: file=report\u$(日期+%Y%m%d) cat不是那样的,但是: cat << EOF | sh > $file date hostname echo 'End of Report' EOF cat$文件 日期 主机名 回显“报告结束” EOF 也会达到同样的效果。(请注意,这是一个新的sh命令,如果需要,可以使用bash,而不是当前shell的子shell,因此它没有
file=report\u$(日期+%Y%m%d)
cat不是那样的,但是:
cat << EOF | sh > $file
date
hostname
echo 'End of Report'
EOF
cat$文件
日期
主机名
回显“报告结束”
EOF
也会达到同样的效果。(请注意,这是一个新的sh
命令,如果需要,可以使用bash
,而不是当前shell的子shell,因此它没有设置相同的变量。)
(编辑:我没有注意到这也是一个UUOC:Cat的无用用法;请参见爆炸药丸的答案:-)您可以使用sh
(或bash
)作为命令,而不是Cat
;它将实际作为shell脚本运行:
sh <<EOF > $file
date
hostname
echo 'End of Report'
EOF
sh如果要将所有行作为命令展开,则herdeoc无效:
file="report_$(date +%Y%m%d)"
{
date
hostname
echo 'End of Report'
} >| "$file"
您也可以像这样重定向1>
:
file="report_$(date +%Y%m%d)"
exec 1> "$file"
date
hostname
echo 'End of Report'
这似乎对我不起作用;它似乎认为heredoc是未关闭的两个很好的答案,但爆炸药丸似乎稍微多一些straightforward@torek我只是抄了你的;也许是另一个贝壳version@Lighthart人们似乎总是忘记,从贝壳和从管子中读取标准数据是没有区别的;当cut file
做同样的事情时,我经常看到像cat file | cut
这样的事情。@ExplosionPills:看起来像是剪切和粘贴在某种程度上(在“EOF”位之前)插入了一些额外的空白。我会责怪键盘上的猫,但我打字时她不在这里…:-)
file="report_$(date +%Y%m%d)"
{
date
hostname
echo 'End of Report'
} >| "$file"
file="report_$(date +%Y%m%d)"
exec 1> "$file"
date
hostname
echo 'End of Report'