Home > OS >  The command returns a value acquisition in the $()
The command returns a value acquisition in the $()

Time:09-17

The command standard output when assigned to a variable, how to obtain the return value of the command?
For example:

A=$(command1 | command2 | command3)

My goal is to be able to get to the command1 return values, if the return value is zero, the exit, if return a value of 0, continued,

Baidu for a long time, also please feel free to comment, thank you!

CodePudding user response:

$(command1 | command2 | command3) of the return value is the command3 return values,
If you need to determine the return values of command1 can consider first carry out command1 independently, and then judge;
But that there is a premise: command1 return values can be repeated, which means command1 no matter how many times to perform, the return value is the same, (i.e. command1 is a query, rather than change, will not change the resource state)

 
If command1 & gt;/dev/null
Then
A=$(command1 | command2 | command3)
Echo "$a"
The exit 0
The else
Echo "failed to execute command1"
The exit 1
Fi

CodePudding user response:

reference 1st floor mymtom response:
$(command1 | command2 | command3) of the return value is the command3 return values,
If you need to determine the return values of command1 can consider first carry out command1 independently, and then judge;
But that there is a premise: command1 return values can be repeated, which means command1 no matter how many times to perform, the return value is the same, (i.e. command1 is a query, rather than change, will not change the resource state)

 
If command1 & gt;/dev/null
Then
A=$(command1 | command2 | command3)
Echo "$a"
The exit 0
The else
Echo "failed to execute command1"
The exit 1
Fi
I considered this way, it seems there is no way to perform a get the return values of command1 because command1 execution is slow, want to execute only once to obtain the return value is in order to promote efficiency, the way you can be right, but has changed with my original intention, and thank you very much for your answer!
  • Related