Script command explanation
Suppose I have a script with four lines as follows:
command1 command2 command3 command4 If command2 gives an error does the script proceed to command3, or does it stop? If so, is it essentially the same as: command1 && command2 && command3 && command4 |
No, the && means command2 will only run if command1 completed successfully and so on.
command1 command2 ... command2 will run regardless if command1 ran successfully. |
Why don't you try/experiment/test it for yourself.
Code:
#!/usr/bin/bash |
|
It seems I have to use (set -e).
Is there anything I can do to find out which line gave the error? |
"set -x" will output certain commands, after expansions, but before executing.
It's quite common to apply these to the shell/bash command - e.g. "#!/usr/bin/bash -ex" - try that with teckk's script to see how it works. The benefit of "set" is you can turn the options on/off for relevant parts of a script (Though confusingly, set uses "+" to turn things off.) Also, if you haven't already, ShellCheck can be used to highlight common errors. |
I tried teckk's script and also a second time I used (-ex) at the end of the hashbang line, I have seen no difference.
Trying that with the set -e as a second line closed the terminal window after pressing enter, no error output. Never mind about that though. With the set -e option, I can place that line anywhere, let's say at the beginning of a script, and to unset it at line 50 for instance, I have to insert a line as (set +). Did I get that right? And there is nothing that can show me which line or command gave me an error? I am planning to automate LFS as much as I can and I do expect a few errors at least (on a good day). I am planning to make it in 3-4 sections and then combine it (the file will be long at the end). |
Or can I direct the output to a file to find out where the error was?
|
Quote:
Code:
#!/usr/bin/bash Code:
bash ./test1.sh |
Good one, what I need. And that was a nice example teckk.
Thanks to all. Have a nice day/night. |
Quote:
Anyway, here's a quick example - it has the same effect whether you are running Bash yourself, or whether execve is calling it as "#!/path/to/bash" (although one important distinction is the latter passes only a single argument to the interpreter). Code:
$ bash -c 'echo one;ech two;echo three' Quote:
|
what was missing:
I would suggest to use: Code:
set -o errexit # set -e nounset is used to stop if someone tries to use an undefined variable. set -o xtrace (or set -x) is used to print a lot of debug messages, this was described before. |
And for consistency/completeness, "set -o nounset" is the same as "set -u"
The benefit of the single-letter options over option names is the ability to combine them in a single argument/command. "help set" provides a convenient reminder of what's what. |
Also there is set -o pipefail
Example: Code:
set -e Code:
set -e |
All times are GMT -5. The time now is 03:07 PM. |