AlexSalas95
New User
.jpg)
Joined: 18 Mar 2024 Posts: 21 Location: United States
|
|
|
|
@NEW2MAIN I'm assuming by now you've figured this out or have some other workaround/solution, so I'll put this out for progeny.
Unless you specifically capture and handle the return code for a particular command, the script will return the result of the last command executed.
For example, cd'ing to a non-existent directory should result in an rc=1; however, if afterward you echo out an error message, that command executes successfully, and the result is an rc=0.
This is a bit dangerous. To demonstrate, let's assume the current directory is as follows;
| Code: |
$ ls
folder1 folder2 text.txt
|
Now consider the following script;
| Code: |
$ cd folder3 # this does not exist
$ mkfile newtext.txt
|
Note that folder3 does not exist. So, what happens? Well, the error is written to the log, but the script continues. The newtext.txt file is created in the active directory. So now the current directory looks like this;
| Code: |
$ ls
folder1 folder2 newtext.txt text.txt
|
Also, since the mkfile and ls commands were executed successfully, the return code for the script is 0.
There are probably several ways to handle this. Perhaps the best way is if there is an environment variable/parameter that will exit the script as soon as a command fails. I'm not sure if such a way exists. However, the way I've handled it is to capture and process the return code for commands deemed critical for the execution of the script. You can reference the return code (more specifically, the exit code, but that semantics) for the previously executed command by the $? shell variable. This is how that would look;
| Code: |
$ cd folder3 # this does not exist
if $? > 0 ; then
exit
fi
$ mkfile newtext.txt
$ ls |
When the above is executed, the return code will be rc=1, and neither the mkfile nor ls commands are executed. To set a different return code, simply follow the exit command with the code, like "exit 8" to return rc=8.
To make the code more modular and less repetitive, you could move the logic to check the return code into a function and call this function after each critical command is called. That way, you are sure to exit the script when something goes wrong and get the corresponding return code.
Hopefully this is helpful to someone, and if somebody knows of a better way, feel free to share! |
|
AlexSalas95
New User
.jpg)
Joined: 18 Mar 2024 Posts: 21 Location: United States
|
|
|
|
| To put it simply, add logic to check the exit codes using the $? shell variable, and specify return codes using exit $? or exit x, where x is the desired return code. |
|