Is there a way to mark a script to be executed in the current shell from whitin It? I know I can use:
. ./path/myscript.sh
but I need a way to include the "dot" way inside the script.
Edit: Here is the case. I have a script "myscript.sh" located in directory A:
rm -r A
mkdir A
touch A/test.file
cd A
When the script is executed in normal a way:
sh myscript.sh
When exiting the script I cannot list the directory. When script is started in the current shell:
. ./myscript.sh
There is no problem. I need a way to include this "dot" way inside my script so It can be called without It.
There are two ways of executing a script in the shell. Depending upon your needs, you will have to do one of the following (don't do both!).
To launch the script as a program:
#!/bin/bash
as the first line of the scriptThis will be read by the loader, which has special logic that interperts the first two characters #!
as "launch the program coming next, and pass the contents into it". Note this only properly works for programs written to receive the contents
To source the script into the current shell:
. script.sh
or source script.sh
Note: .
in bash is equivalent to source
in bash.
This acts as if you typed in the contents of "script.sh". For example, if you set a variable in "script.sh" then that variable will be set in the current shell. You will need to undefine the variable to clear it from the current shell.
This differs heavily from the #!/bin/bash
example, because setting a variable in the new bash
subprocess won't impact the shell you launched the subprocess from.
You can do this if you create a shell function instead of a script. Functions are executed in the same shell, not a subshell. If you define functions in your .profile, they will be available to the login-shell.
I found some more details and explanations here: http://steve-parker.org/sh/functions.shtml
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With