Continuous execution uses semicolons. sometimes we want to write multiple commands under the command line. In this case, how can we perform this operation. # Ls/tmp/xxxx; echo & #39;/tmp/xxxx & #39; ls:/tmp/xxxx: nosuchfileordirectory/tmp/xxxx in General/tmp/directory, there is no xxxx file. I am blind to write this file, mainly used to show that execution fails. However
Use semicolons for continuous execution
Sometimes we want to write multiple commands under the command line. In this case, how can we perform this operation. As follows:
#ls /tmp/xxxx ; echo '/tmp/xxxx'ls: /tmp/xxxx: No such file or directory/tmp/xxxx
Generally, no xxxx file exists in the/tmp/directory. I am blind to write this file, mainly used to show that execution fails.
However, we only considered continuous execution. if the first command fails, the second command will still be executed, that is, there is no correlation between commands. how can we make the first command run successfully before executing the second command, or, if the first command fails to be executed, the second command will be executed.
Variable $? To judge execution
// When the previous command is not successfully executed, $? Output 1 # ls/tmp/xxxx; echo $? Ls:/tmp/xxxx: No such file or directory1 // Create an xxxx file # touch/tmp/xxxx // when the previous command is successfully executed, $? Output 0 # ls/tmp/xxxx; echo $? /Tmp/xxxx0
If the command is successfully executed, $? The variable is assigned a value of 0. Otherwise, the value is-1. By judging $? The variable method can indeed meet our requirements, but we need to use if to judge whether to write a script is complicated. Is there any convenient command. Haha, there must be some.
Shell also provides the shortcut operators: & and |
// The/tmp/xxxx file exists at this time, run the & Command # ls/tmp/xxxx & echo '/tmp/xxxx exits ///tmp/xxxx file, do not execute | subsequent command # ls/tmp/xxxx | echo '/tmp/xxxx exits'/tmp/xxxx
We can analyze this in the previous example. if the & signature command is successfully executed, the subsequent command is executed. | the subsequent command is executed only when the previous command fails to be executed.
So what is the execution sequence when there are multiple &, |?
The following example is used to determine whether/tmp/aaaa exists and output the result.
# ls /tmp/aaaa && echo "exist" || echo "not exist"ls: /tmp/aaaa: No such file or directorynot exist# touch /tmp/aaaa# ls /tmp/aaaa && echo "exist" || echo "not exist"/tmp/aaaaexist
Therefore, we only need to judge from left to right. Note: If | or & the command is not executed, it will be processed as an execution failure.