Question

My understanding is that when I execute a script inside a BASH shell using syntax like $ ./myscript.sh a sub-shell is started and the code runs in that shell, with STDOUT and STDERR output being printed on my shell, STDIN is taken from my shell. This is how script are interactive.

The top line of the file "myscript" is #!/bin/bash, this states the interpreter to be used to execute the syntax within the script file.

If I use the syntax source myscript.sh the code in my script is "pulled" in to my current environment and executed there, rather than in a sub-shell. I can't make the following code run in a script that I call with $ ./myscript.sh and effect my current shell:

#!/bin/bash

PS1='`
  if [ $? -eq 0 ];
    then echo -n "\[\033[00;35m\]\u\[\033[01;32m\]@\[\033[00;35m\]\h\[\033[00;32m\](\[\033[01;35m\]\W\[\033[01;32m\])\[\033[00;32m\]\$";
    else echo -n "\[\033[00;35m\]\u\[\033[01;31m\]@\[\033[00;35m\]\h\[\033[01;31m\](\[\033[35m\]\W\[\033[31m\])\[\033[00;31m\]\$";
  fi`\[\033[0m\]'

If I drop the #!/bin/bash and use source this script changes my command prompt. Can it be arranged in a script in such a fashion that I can call it with $ ./myscript.sh and it will make the change to my current shell, not the sub shell?

Was it helpful?

Solution

Once you have called a script without source, it is running in a subshell and there is no way to change the environment of the parent shell.

You can source a script with a shebang line. It is simply ignored when sourced.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top