What are the methods of judging the return value of shell command
This article mainly introduces the shell command return value judgment method of what is the relevant knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe that after reading this shell command return value judgment method which articles will have a harvest, let's take a look at it.
1. Determine whether a command has an elegant method 1
First, the idiomatic method of checking whether a command is valid is directly in the if statement.
If command; then echo notify user OK > & 2else echo notify user FAIL > & 2 return-1fi
(good practice: use > & 2 to send messages to stderr. )
Elegant method 2
Transfer generic logic to a shared function.
Check () {local command= ("$@") if "${command [@]}"; then echo notify user OK > & 2 else echo notify user FAIL > & 2 exit 1 fi} check command1check command2check command3 elegant method 3installed () {command-v "$1" > / dev/null 2 > & 1} if installed then xxelse xxx fi2. Return error exit 1. | | exit exit command1 | | exitcommand2 | | exitcommand3 | | exit2. Use-e $bash-e xx.shroud command1command2command33 to bind a command1command2command33 to bash-e xx.shcommand1command2command33.set-e $bash xx.shrunken to Bin / bin-e. Return the general method of error prompt:
Method 1
If do some command; then echo notify user OKelse echo notify user fail exit 255 # exit code must be unsigned shortfi
Method 2
Do some commandif [$?-eq 0]; then echo notify user OKelse echo notify user FAIL return-1fi elegant method
Method 1
Die () {local message=$1 echo "$message" > & 2 exit 1} command1 | | die 'command1 failed'command2 | | die' command2 failed'command3 | | die 'command3 failed'
Method 2 (recommended)
Warn () {echo "$@" > & 2} die () {status= "$1" shift warn "$@" exit "$status"} do some command & & echo notify user OK | | die 255Notify user fail on "what are the methods for determining the return value of the shell command". Thank you for reading! I believe you all have a certain understanding of the knowledge of "what is the method of judging the return value of the shell command". If you want to learn more, you are welcome to follow the industry information channel.