可能重复:
捕获多行输出到bash变量
我有可能是一个基本的脚本问题,但我无法在任何地方找到答案.
我有一个处理文件的awk脚本,并吐出一系列已禁用的系统.当我从命令行手动调用它时,我得到格式化输出:
$awk -f awkscript datafile
The following notifications are currently disabled:
host: bar
host: foo
Run Code Online (Sandbox Code Playgroud)
我正在编写一个包装脚本来从我的crontab调用,它将运行awk脚本,确定是否有任何输出,如果有,则给我发电子邮件.它看起来像(简化):
BODY=`awk -f awkscript datafile`
if [ -n "$BODY" ]
then
echo $BODY | mailx -s "Disabled notifications" me@mail.address
else
echo "Nothing is disabled"
fi
Run Code Online (Sandbox Code Playgroud)
当以这种方式运行,并通过echo $BODY
在脚本中添加一个确认时,输出被剥离格式化(换行符主要是我关注的),所以我得到的输出看起来像:
The following notitifications are currently disabled: host: bar host: foo
Run Code Online (Sandbox Code Playgroud)
我试图找出如果我手动运行命令时如何保留存在的格式.
到目前为止我尝试过的事情:
echo -e `cat datafile | awkscript` > /tmp/tmpfile
echo -e /tmp/tmpfile
Run Code Online (Sandbox Code Playgroud)
我试过这个,因为在我的系统(Solaris 5.10)上,使用echo而没有-e忽略标准转义序列,如\n.没工作.我检查了tmp文件,它没有任何格式,因此在存储输出时会出现问题,而不是在打印输出时.
BODY="$(awk -f awkscript datafile)"
echo -e "$BODY"
Run Code Online (Sandbox Code Playgroud)
我试过这个,因为我能找到的一切,包括stackoverflow上的其他一些问题,说问题是shell如果没有引用,它会用空格替换空格代码.没工作.
我尝试使用printf而不是echo,使用$(命令)而不是`command`,并使用tempfile而不是变量来存储输出,但似乎没有任何东西保留格式.
我错过了什么,或者有其他方法可以避免这个问题吗?
BODY=`awk -f awkscript datafile`
if [ -n "$BODY" ]
then echo "$BODY" | mailx -s "Disabled notifications" me@mail.address
else echo "Nothing is disabled"
fi
Run Code Online (Sandbox Code Playgroud)
请注意中的双引号echo
.
您也可以简化此版本:
echo -e `cat datafile | awkscript` > /tmp/tmpfile
echo -e /tmp/tmpfile
Run Code Online (Sandbox Code Playgroud)
只是:
tmpfile=/tmp/tmpfile.$$
awkscript > $tmpfile
if [ -s $tmpfile ]
then mailx -s "Disabled notifications" me@mail.address < $tmpfile
else echo "Nothing is disabled"
fi
Run Code Online (Sandbox Code Playgroud)
反引号很有用(但写得更好$(cmd args)
)但不必在任何地方使用.