How to execute script in the current shell on Linux?
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.
Solution 1:
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!).
- Launch the script as a program, where it has its own process.
- Source the script as a bunch of text, where the text is processed by the current shell.
To launch the script as a program:
- Add the line
#!/bin/bash
as the first line of the script
This 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:
- type the command
. script.sh
orsource 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.
Solution 2:
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
Solution 3:
One thing you can do is to add the function to your .bash profile. Then running the function won't be running a script.
I'll try it now...
testit() {
rm -r A
mkdir A
touch A/test.file
cd A
}
works...
so another option is to create a file with the function definition in it, and source that file.