How to execute script in the current shell on Linu

2019-05-21 10:08发布

问题:

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.

回答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!).

  1. Launch the script as a program, where it has its own process.
  2. 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 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.



回答2:

  1. put #!/bin/sh as the first line of the script
  2. Add execute permission i.e. chmod +x /path/to/script.sh

Then you can run the script

i.e. /path/to/script.sh

or if you have /path/to in the PATH environment variable you can simply execute script.sh



回答3:

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



回答4:

Try this: source path/to/shell/script.sh

It will execute the shell script in current shell.



标签: linux shell