Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute script in the current shell on Linux?

Tags:

linux

shell

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.

like image 843
kofucii Avatar asked Feb 07 '13 06:02

kofucii


2 Answers

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.

like image 73
Edwin Buck Avatar answered Oct 12 '22 13:10

Edwin Buck


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

like image 32
Rolf Rander Avatar answered Oct 12 '22 15:10

Rolf Rander