-4

I'm running the following script at home that I found online and every time I do, the shell terminates when I supply an answer to the read prompt. When I run the script in the bg, I get the following message: Bash: [answer]: command not found. Why is this happening? I usually run it from the directory the script is kept using .

Edit: I ran the script with bash instead, and the script worked as expected. Can anyone explain why the difference?

#!/bin/bash

echo "Enter 1 or 2, to set the environmental variable EVAR to Yes or No"
read ans

# Set up a return code
RC=0

if [ $ans -eq 1 ]  
then 
    export EVAR="Yes"
else
    if [ $ans -eq 2 ]
    then
    export EVAR="No"
    else
# can only reach here with a bad answer
    export EVAR="Unknown"
    RC=1
    fi    
fi
echo "The value of EVAR is: $EVAR"
exit $RC

1 Answers1

2

It's pretty much the same answer as for your otherwise-identical question on SuperUser.

When you run a shell script with . (or source) you are running it in the context of your interactive shell. Thus, when the shell hits an exit command it exits your interactive shell.

The correct way to run a shell script is not to use . (or source) but to make it executable and just run it as if it were any other application. (The first line, starting with #!, defines the interpreter for the script. In my example it's /bin/bash but it could be anything that can read a script.)

Here is a worked example for a script that's called tryit:

# Create a trivial shell script called "tryit"
cat >tryit <<'X'
#!/bin/bash
echo "This is my shell script"
exit 0
X

# Make it executable
chmod +x tryit

# Now run it (the "./" prefix means "in the current directory")
./tryit

If you put the tryit script into a directory that is in your $PATH you don't need (and must not use) the ./ prefix. Here is an example

# Create applications (bin) directory and add to PATH for this session
mkdir -p "$HOME/bin"
export PATH="$HOME/bin:$PATH"

# Move the "tryit" application to the bin directory
mv tryit "$HOME/bin"

# Now we can run it just like any other application
tryit

I should probably point out that when running a script this way it is not possible to set environment variables in the current interactive shell. To do that you really do need to continue using . or source, in which case you must remember that because the script runs in your interactive context you must not include an exit statement anywhere.

Chris Davies
  • 116,213
  • 16
  • 160
  • 287