制作,将打印可选参数的函数。
stop()
{
if [ $# -gt 0 ]; then
echo "Failed: [email protected]"
else
echo "Failed."
fi
exit 1
}
如果您不想编写大量代码,则可以使用不带参数的函数。
cd /home/lin || stop
mkdir logs || stop
cp /tmp/filelog.log logs/ || stop
rm /tmp/log* || stop
touch /tmp/log || stop
echo Success
您可以投入更多精力。
第一个命令显示如何提取stderr并在输出中使用它。
errmsg=$(cd /home/lin 2>&1) || stop ${errmsg}
# You do not want an error when the dir already exists
mkdir -p logs || stop
# You can test in front
test -f /tmp/filelog.log || stop File filelog.log not found
cp /tmp/filelog.log logs/ || stop
rm -f /tmp/log* || stop
touch /tmp/log || stop
echo Success
其他的可能性是使用set -e
(会失败后退出,但不会有“失败”的消息),这是在@Kusalananda和@HenkLangeveld的答案中。
或者使命令的链:
cd /home/lin &&
mkdir -p logs &&
test -f /tmp/filelog.log &&
cp /tmp/filelog.log logs/ &&
rm -f /tmp/log* &&
touch /tmp/log || stop
晶莹剔透:) –
我测试,它没有工作为了我。并且(不是必需的)在subshell中设置的变量将会丢失。 –