Sometimes, the execution path of the entire shell script file is determined based on the command execution result status.
A simple requirement is to determine whether a row of content exists in a file. If yes, no operation is performed. Otherwise, the row is inserted.
To determine whether a row exists in the file, run the grep command: grep $ line $ file.
If $ line exists in $ file, the result returned by grep execution is 0. If no result exists, 1 is returned. If $ file does not exist, 2 is returned.
We can use the following shell code for simple verification:
#/Bin/bashgrep "ABC" filenamereval =$? Echo "grep return value: $ reval" Exit 0
If you replace grep "ABC" filename in the preceding shell file with other required commands, you can print the execution result status at the end of the command.
But it is troublesome to modify the shell file every time. We can use the "·" symbol to directly test the file in the terminal window. Before "·" is closed, commands are not executed.
:~ $ Echo '> grep "ABC" FILENAME> reval = $?> Echo "grep return value: $ reval"> exit 0> 'grep: Filename: no such file or directorygrep return value: 2iie @ haproxy091 :~ $
As shown in the prompt, 2 is returned for grep execution because the file filename is found.