user6934519
user6934519

Reputation:

Is there a way in the shell script that if [ <script exits with non-0 value> ] then; do <something>

In the shell script, I want to do that if the shell script failed ( exited with non zero value), then before exiting the process, do something.

How could I insert such a if statement block in my shell script.

Is that feasible?

For example,

set -e
echo $password > confidential.txt
rm <file-that-does-not-exist>
rm confidential.txt

I want to make sure that the confidential.txt is made sure to be removed anyways

Upvotes: 1

Views: 69

Answers (3)

Charles Duffy
Charles Duffy

Reputation: 295262

Assuming you're on Linux (or another operating system with /proc/*/fd), you have an even better option: Delete confidential.txt before putting the password into it at all.

That can look something like the following:

exec 3<>confidential.txt
rm -f -- confidential.txt
printf '%s\n' "$password" >&3

...and then, to read from that deleted file:

cat "/proc/$$/fd/3"  ## where $$ is the PID of the shell that ran the exec command above

Because the file is already deleted, it's guaranteed to be eligible for garbage collection by your filesystem the moment your script (or the last program it started inheriting its file descriptors) exits or is killed, even if it's killed in a way that doesn't permit traps or signal processing to take place.

Upvotes: 0

choroba
choroba

Reputation: 241738

Use trap with the EXIT pseudo signal:

remove_secret () {
    rm -f /path/to/confidential.txt
}
trap remove_secret EXIT

You probably don't want the file to remain if the script exits with 0, so EXIT happens regardless of the exit code.

Note that without set -e, rm on a non-existent file doesn't stop the script.

Upvotes: 1

Barmar
Barmar

Reputation: 780655

Use the trap command:

trap 'if [ $? -ne 0 ]; then echo failed; fi' EXIT

The EXIT trap is run when the script exits, and $? contains the status of the last command before it exited.

Note that a shell script's exit status is the status of the last command that it executed. So in your script, it will be the status of

rm confidential.txt

not the error from

rm filethatdoesnotexist

Unless you use set -e in the script, which makes it exit as soon as any command gets an error.

Upvotes: 3

Related Questions