[转]How to determine the exit status of Linux and UNIX command

Shell: How to determine the exit status of Linux and UNIX command
by NIXCRAFT on FEBRUARY 11, 2006 · 14 COMMENTS· last updated at JUNE 1, 2008

Q. Can you explain the exit status of shell and commands under Linux / UNIX operating system?

A. All UNIX and Linux command has a several parameters or variables that can be use to find out the exit status of command. Please note that these parameters or variables may only be referenced assignment to them is not allowed. You can use $? to find out the exit status of command. $? always expands to the status of the most recently executed foreground command or pipeline. For example, you run the command cal:
$ cal

Now to see exit status of cal command type following command:
$ echo $?

Output:

0
Zero means command executed successfully, if exit status returns non-zero value then your command failed to execute. For example run command called cyberciti
$ cyberciti

Output:

bash: cyberciti: command not found
Display exit status of the command:
$ echo $?

Output:

127
Value 127 (non-zero) indicates command cyberciti failed to execute. You can use exit status in shell scripting too. You can store result of exit status in variable. Consider following shell script:

#!/bin/bash
echo -n "Enter user name : "
read USR
cut -d: -f1 /etc/passwd | grep "$USR" > /dev/null
OUT=$?
if [ $OUT -eq 0 ];then
echo "User account found!"
else
echo "User account does not exists in /etc/passwd file!"
fi

Save and execute the script as follows:
$ chmod +x script.sh
$ ./script.sh

Output:

Enter user name : jradmin
User account does not exists in /etc/passwd file
Try it one more time:
$ ./script.sh

Output:

Enter user name : vivek
User account found
As you can see, I have used grep command to find out user name stored in USR variable. If grep command finds user name in /etc/passwd command output it would return exit status of zero. This is stored in OUT variable. Next, if command makes decision based upon exit status stored in OUT variable.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值