加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何逐行执行bash脚本?

发布时间:2020-12-16 01:49:35 所属栏目:安全 来源:网络整理
导读:参见英文答案 Automatic exit from bash shell script on error????????????????????????????????????8个 #Example Scriptwget http://file1.comcd /dirwget http://file2.comwget http://file3.com 我想逐行执行bash脚本并测试每次执行的退出代码($?)并确
参见英文答案 > Automatic exit from bash shell script on error????????????????????????????????????8个

#Example Script
wget http://file1.com
cd /dir
wget http://file2.com
wget http://file3.com

我想逐行执行bash脚本并测试每次执行的退出代码($?)并确定是否继续:

它基本上意味着我需要在原始脚本的每一行下面添加以下脚本:

if test $? -eq 0 
then
    echo "No error"
else
   echo "ERROR"
   exit
fi

并且原始脚本变为:

#Example Script
wget http://file1.com
if test $? -eq 0 
then
    echo "No error"
else
   echo "ERROR"
   exit
fi
cd /dir
if test $? -eq 0 
then
    echo "No error"
else
   echo "ERROR"
   exit
fi
wget http://file2.com
if test $? -eq 0 
then
    echo "No error"
else
   echo "ERROR"
   exit
fi
wget http://file3.com
if test $? -eq 0 
then
    echo "No error"
else
   echo "ERROR"
   exit
fi

但剧本变得臃肿.

有更好的方法吗?

解决方法

一个人可以使用 set -e but it’s not without it’s own pitfalls.另一个可以拯救错误:

command || exit 1

你的if语句可以写得更简洁:

if command; then

以上内容与:

command
if test "$?" -eq 0; then

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读