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:
Now to see exit status of cal command type following command:
$ echo $?
Zero means command executed successfully, if exit status returns non-zero value then your command failed to execute. For example run command called cyberciti
bash: cyberciti: command not found
Display exit status of the command:
$ echo $?
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
Enter user name : jradmin User account does not exists in /etc/passwd file
Try it one more time:
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.Tweet itFacebook itG+ itDownload PDF versionFound an error/typo on this page?
- 30 Cool Open Source Software I Discovered in 2013
- 30 Handy Bash Shell Aliases For Linux / Unix / Mac OS X
- Top 30 Nmap Command Examples For Sys/Network Admins
- 25 PHP Security Best Practices For Sys Admins
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- 20 Linux Server Hardening Security Tips
- Linux: 20 Iptables Examples For New SysAdmins
- Top 20 OpenSSH Server Best Security Practices
- Top 20 Nginx WebServer Best Security Practices
- 20 Examples: Make Sure Unix / Linux Configuration Files Are Free From Syntax Errors
- 15 Greatest Open Source Terminal Applications Of 2012
- My 10 UNIX Command Line Mistakes
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- The Novice Guide To Buying A Linux Laptop