3

I would like to set a variable inside .bashrc to be equal to the output of a command that may return an error code.

I do not know the implications of doing such a thing. Will everything else work correctly even if this command fails?

The code in .bashrc currently is simply:

export MYVAR=$(my_dubious_command 2>/dev/null)

Is it safe to do this?

  • 2
    If you want to be sure that an uncaught error won't cause a problem, add ` || :` to the end of the commandline to eat any potentially thrown error. For instance, myvar="$(/bin/false 2>/dev/null)" || :. This will also work in scripts in which set -e is used. – DopeGhoti Jun 9 '17 at 17:35
2

As l0b0 said, it's unlikely that your .bashrc would be running with errexit set, but you could take care of that situation by testing:

case $SHELLOPTS in
  (*errexit*)   set +e;
                export MYVAR=$(my_dubious_command 2>/dev/null);
                set -e
                ;;
  (*)           export MYVAR=$(my_dubious_command 2>/dev/null)
                ;;
esac

The export command, as written, should return 0, in case any subsequent commands check $?; you are not providing any invalid options to it, the variable name is a valid one, and you are not exporting a non-existent function.

The case statement checks to see if errexit is set; if so, it temporarily turns it off in order to run my_dubious_command.

3

Let's try:

$ var=$(false)
$ echo $?
1
$

However, it is unlikely that you have errexit set in your .bashrc, and even less likely that the next command checks the exit code of your command, so it's very unlikely that it will affect anything.

Startup scripts like .bashrc are one place where you do not want to set -o errexit, because you can be blocked out of the shell by a simple typo or changes you are not in control of. To detect but not fail because of errors you can for example trap them:

$ trap 'echo $?' ERR
$ var=$(false)
1
$

This is quite useful in the prompt, for example.

  • By the way, I am using export (sorry I didn't write it clearly in my question). It seems export swallows the error code; I don't know if the question is still valid. – Alberto Rivera Jun 9 '17 at 18:25
  • Yes, export does swallow the exit code. There can only be one exit code per command, and in that case export throws the command exit code away and returns its own. – l0b0 Jun 9 '17 at 18:28
  • 1
    @AlbertoRivera, you may also want to see: unix.stackexchange.com/a/281749/135943 – Wildcard Jun 9 '17 at 22:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.