开发者

How to check if a shell command executed properly or not?

开发者 https://www.devze.com 2023-01-16 22:41 出处:网络
#!/bin/sh tar=$1 if [ -f $tar ] then tar xvf $tar else exit 1 fi ... <more code> I need a conformation that the tar actually happened successfully, otherwise abort the execution of the 开发者
#!/bin/sh
tar=$1
if [ -f $tar ]
then
    tar xvf $tar
else
    exit 1
fi

... <more code>

I need a conformation that the tar actually happened successfully, otherwise abort the execution of the 开发者_Python百科script.

The tar file extract might not go through because

  • some problems with tar command
  • access issues with $tar

Do Linux utilities have some return values? How should I use them here?


Check the $? variable after executing a command. If everything is OK, it should be 0, positive otherwise.

tar xvf $tar
[ $? -ne 0 ] && exit 1

More information here.


This

tar xvf "$tar" || exit 1

or this (if you want to check if file exists yourself)

[ -f "$tar" ] && tar xvf "$tar" || exit 1
0

精彩评论

暂无评论...
验证码 换一张
取 消