1

I caught myself out; I couldn't log into root after I made a script and called it from ~/.bashrc.

~/.bashrc:

#... do stuff then run my script
source ~/myscript.sh

~/myscript.sh:

#!/bin/bash
if [myConditional]; then
  exit
fi
# otherwise do stuff

What I had hoped was that when I log in as root, myscript.sh would be run, and if myConditional was true, myscript.sh would stop running any further commads, but would return to .bashrc and the user would still be logged in as root as usual. But instead, exit stopped me from being able to log in at all! It just returned me to a login prompt.

Is there another command I should be using besides exit? Obviously I could just extend the if statement by having an else statement and removing exit, but for educational purposes I'd like to know if there is a more appropriate approach. (Also partly because I want to avoid deeply nested if statements; it could be quite a large script)

Jodes
  • 217

1 Answers1

3

source filename.sh (or . filename.sh) runs the contents of filename.sh in the current interpreter (essentially, as though you copied the contents in at that point). Consequently, exit will exit that interpreter.

If you just want to run the script as a separate program, don't use source: just ~/myscript.sh will run it if you make it executable first with chmod +x ~/myscript.sh, or you can use bash ~/myscript.sh if you prefer. That starts up a new shell to run your script, just like if it were any other program on the system.

On the other hand, if you do really mean to source your script (because it's going to set environment variables, say), you can stop running the rest of the file without affecting .bashrc and the shell that ran it using return:

return may also be used to terminate execution of a script being executed with the . (source) builtin, returning either n or the exit status of the last command executed within the script as the exit status of the script

In that case, your myscript.sh file would have:

if [[ condition ]]
then
    return 0
fi

with the effect you wanted.

Michael Homer
  • 76,565