Not able exit from docker container with bash script containing exit command

Viewed 1467

I'm able to exit when I enter the exit command in container environment. But if I try to run a script file having the exit command, I'm not able to exit from the container.

1.working

ubuntu@iot-docker:/repo$ exit
exit
 
root@iot-docker:/repo# exit
exit

ubuntu@ubuntu-***-Twr:~/shirisha/plo-***-snt-sp_u103a3$ 

  1. not working
script.sh
   
#!/bin/bash
exit
   
exit
2 Answers

exit is not a command to exit your container, it just exits the current shell interpreter.

When you run your script, a new shell interpreter is started according to the first line of your script (here /bin/bash). When it encounters the exit command, the interpreter stops and you get back to the command line (the previous shell).

You can make this expriment:

$ bash     # Starts a new shell
$ exit     # Exits the new shell; we come back to the old one
exit
$ 

See? Running bash in command line is similar to running your script, and exiting from it brings you back to your previous shell. You didn't exit your container.

Solution:

exec script.sh param1 ... paramN

exec will replace your current shell with the command being started (script.sh). When that command exits, you will exit your container because your old shell no longer exists.

When you script a script without "sourcing" the script, the script will be started in a new subprocess. The exit works, you will finish that subprocess.
It is important to remember, that a script starts a new environment.

Look at the script example.sh

#!/bin/bash
my_value=high
cd /tmp

Call this script with

cd $HOME
my_value="low"
./example.sh
pwd
echo "My value is now ${my_value}"

Now nothing has changed: all changes in the subprocess are gone.
You can call this script with source ./example.sh (or short . ./example.sh), and things have changed.

When you don't want to source your script, a function (in .bashrc) might help:

example() {
   my_value=high
   cd /tmp
}

Now you can call the function:

cd $HOME
my_value="low"
example
pwd
echo "My value is now ${my_value}"
Related