About $?


$? indicates the end code of the last command run

 

Test Example 1

root@bosh:~# cat a
exit 2
root@bosh:~# sh a
root@bosh:~# echo $?
2
root@bosh:~# cat a | grep exit
exit 2
root@bosh:~# echo $?
0
root@bosh:~# cat a | grep hello
root@bosh:~# echo $?
1
root@bosh:~#

 

测试示例2
[root@updb-new1 ~]# mysql -uroot -e "show databases"
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| test               |
+--------------------+
[root@updb-new1 ~]# echo $?
0
[root@updb-new1 ~]# mysql -uroot -e "show databases"|grep test2
[root@updb-new1 ~]# echo $?
1
[root@updb-new1 ~]#

 

Description:
1. The exit value is 0, which means the execution is successful, or there is a matching record.
2. On the contrary, there is no successful execution, or there is no matching record.

 

Typical usage scenarios

When actually writing the script, the following if statement can be used to judge whether the command in the previous step is executed successfully.

if [ $? -ne 0 ]
then
echo 'Execution error or no related records found, etc.'
be

 

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326941479&siteId=291194637