2017-09-02 278 views
0

我想准备一个shell脚本,它将执行我所有的命令,如果我的所有命令都成功了,那么它会打印“SUCCESS”,任何一个命令失败,然后打印“失败”。Shell - 在IF中运行一堆命令

我的shell脚本命令:

cd /home/lin 

mkdir logs 

cp /tmp/filelog.log logs/ 

rm /tmp/log* 

touch /tmp/log 

保存此文件test.sh

这里是我的查询,

在执行这一点,如果我的命令中的任何一个失败那么它应该停止执行并打印“失败”

Else prin T“SUCCESS”

回答

1

样品适当的脚本

#!/bin/sh 

die() { echo >&2 "$0 Err: [email protected]" ; exit 1 ;} 


cd /home/lin    || die "Can't change to '/home/lin' dir" 

mkdir logs     || die "Can't create '$PWD/logs' dir" 

cp /tmp/filelog.log logs/ || die "Can't copy 'filelog.log' to '$PWD/logs'" 

rm /tmp/log*    || die "Can't remove '/tmp/log*'" 

touch /tmp/log    || die "Can't touch /tmp/log" 


echo SUCCESS: All done! 
2

因为每个命令是依赖于它的前身,这是一个完美的使用情况set -e。在子shell中执行所有工作,并且只需检查子shell的结果。

set -e会在遇到第一个错误时退出当前shell。 (即,当返回非零退出状态。)

(set -e 
    cd /home/lin 
    mkdir logs 
    cp /tmp/filelog.log logs/ 
    rm /tmp/log* 
    touch /tmp/log 
) && echo "SUCCESS" || echo "FAILED" 
+1

晶莹剔透:) –

+0

我测试,它没有工作为了我。并且(不是必需的)在subshel​​l中设置的变量将会丢失。 –

0

制作,将打印可选参数的函数。

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 
0

一种用于bash(或ksh)溶液:

#!/bin/bash 

set -e 
trap 'echo FAILED' ERR 

mkdir test/test 
# etc. 

echo 'SUCCESS' 

-eerrexit)壳选项导致shell退出的ERR陷阱将执行由于命令返回非零退出状态。

测试这个脚本在一个目录下mkdir test/test失败:

bash-4.4$ bash script.sh 
mkdir: test/test: No such file or directory 
FAILED 

测试这个脚本在一个目录下mkdir test/test成功:

bash-4.4$ bash script.sh 
SUCCESS