Bash Exit Codes
The exit code is a number between 0 and 255. This is the value returns to parent process after completion of a child process. In other words, it denotes the exit status of the last command our function.
The exit code value return based on a command or program will successfully execute or not.
- Success – A zero (0) value represents success.
- failure – A non-zero exit-code represents failure.
Example
Write a program to write some content in /tmp/tesfile.txt file and check command executed successfully or not.
1 2 3 4 5 6 7 8 9 | #!/bin/bash echo "hi" > /tmp/tesfile.txt if [ $? -eq 0 ]; then echo "Hurrey. it works" else echo "Sorry, can't write /tmp/tesfile.txt" fi |
Another Example
Write a programme to search a string in a file and check if string present or not.
1 2 3 4 5 6 7 8 9 10 | #!/bin/bash STRING="tecadmin" if grep ${STRING} /etc/passwd then echo "Yeah! string found" else echo "Ooooh, no matching string found" fi |
This program will search if string “tecadmin” present in /etc/passwd file.