programing tip

다른 쉘 스크립트에서 쉘 스크립트를 호출하는 방법은 무엇입니까?

itbloger 2020. 10. 2. 21:48
반응형

다른 쉘 스크립트에서 쉘 스크립트를 호출하는 방법은 무엇입니까?


두 개의 셸 스크립트가 a.sh있으며 b.sh.

b.sh쉘 스크립트 내에서 어떻게 호출 할 수 a.sh있습니까?


이를 수행 할 수있는 몇 가지 다른 방법이 있습니다.

  1. 다른 스크립트를 실행 가능하게 만들고 #!/bin/bash맨 위에 줄을 추가 하고 파일이있는 경로를 $ PATH 환경 변수에 추가합니다. 그런 다음 일반 명령으로 호출 할 수 있습니다.

  2. 또는 다음과 같이 source명령 (별칭 is .)을 사용하여 호출합니다 . source /path/to/script;

  3. 또는 bash명령을 사용하여 실행하십시오. /bin/bash /path/to/script;

첫 번째 및 세 번째 메서드는 스크립트를 다른 프로세스로 실행하므로 다른 스크립트의 변수 및 함수에 액세스 할 수 없습니다.
두 번째 방법은 첫 번째 스크립트의 프로세스에서 스크립트를 실행하고 다른 스크립트에서 변수와 함수를 가져와 호출 스크립트에서 사용할 수 있도록합니다.

두 번째 방법에서는 exit두 번째 스크립트에서 사용하는 경우 첫 번째 스크립트도 종료됩니다. 첫 번째와 세 번째 방법에서는 발생하지 않습니다.


이것 좀 봐.

#!/bin/bash
echo "This script is about to run another script."
sh ./script.sh
echo "This script has just run another script."

이를 수행 할 수있는 몇 가지 방법이 있습니다. 스크립트를 실행할 터미널 :

#!/bin/bash
SCRIPT_PATH="/path/to/script.sh"

# Here you execute your script
"$SCRIPT_PATH"

# or
. "$SCRIPT_PATH"

# or
source "$SCRIPT_PATH"

# or
bash "$SCRIPT_PATH"

# or
eval '"$SCRIPT_PATH"'

# or
OUTPUT=$("$SCRIPT_PATH")
echo $OUTPUT

# or
OUTPUT=`"$SCRIPT_PATH"`
echo $OUTPUT

# or
("$SCRIPT_PATH")

# or
(exec "$SCRIPT_PATH")

이 모든 것은 공백이있는 경로에 적합합니다 !!!


내가 찾고 있던 대답 :

( exec "path/to/script" )

As mentioned, exec replaces the shell without creating a new process. However, we can put it in a subshell, which is done using the parantheses.

EDIT: Actually ( "path/to/script" ) is enough.


Depends on. Briefly... If you want load variables on current console and execute you may use source myshellfile.sh on your code. Example:

!#/bin/bash
set -x
echo "This is an example of run another INTO this session."
source my_lib_of_variables_and_functions.sh
echo "The function internal_function() is defined into my lib."
returned_value=internal_function()
echo $this_is_an_internal_variable

set +x

If you just want to execute a file and the only thing intersting for you is the result, you can do:

!#/bin/bash
set -x
./executing_only.sh
sh i_can_execute_this_way_too.sh
bash or_this_way.sh
set +x

I hope helps you. Thanks.


You can use /bin/sh to call or execute another script (via your actual script):

 # cat showdate.sh
 #!/bin/bash
 echo "Date is: `date`"

 # cat mainscript.sh
 #!/bin/bash
 echo "You are login as: `whoami`"
 echo "`/bin/sh ./showdate.sh`" # exact path for the script file

The output would be:

 # ./mainscript.sh
 You are login as: root
 Date is: Thu Oct 17 02:56:36 EDT 2013

Just add in a line whatever you would have typed in a terminal to execute the script!
e.g.:

#!bin/bash
./myscript.sh &

if the script to be executed is not in same directory, just use the complete path of the script.
e.g.:`/home/user/script-directory/./myscript.sh &


First you have to include the file you call:

#!/bin/bash
. includes/included_file.sh

then you call your function like this:

#!/bin/bash
my_called_function

Simple source will help you. For Ex.

#!/bin/bash
echo "My shell_1"
source my_script1.sh
echo "Back in shell_1"

pathToShell="/home/praveen/"   
chmod a+x $pathToShell"myShell.sh"
sh $pathToShell"myShell.sh"

 #!/bin/bash

 # Here you define the absolute path of your script

 scriptPath="/home/user/pathScript/"

 # Name of your script

 scriptName="myscript.sh"

 # Here you execute your script

 $scriptPath/$scriptName

 # Result of script execution

 result=$?

Assume the new file is "/home/satya/app/app_specific_env" and the file contents are as follows

#!bin/bash

export FAV_NUMBER="2211"

Append this file reference to ~/.bashrc file

source /home/satya/app/app_specific_env

When ever you restart the machine or relogin, try echo $FAV_NUMBER in the terminal. It will output the value.

Just in case if you want to see the effect right away, source ~/.bashrc in the command line.


The top answer suggests adding #!/bin/bash line to the first line of the sub-script being called. But even if you add the shebang, it is much faster* to run a script in a sub-shell and capture the output:

$(source SCRIPT_NAME)

This works when you want to keep running the same interpreter (e.g. from bash to another bash script) and ensures that the shebang line of the sub-script is not executed.

For example:

#!/bin/bash
SUB_SCRIPT=$(mktemp)
echo "#!/bin/bash" > $SUB_SCRIPT
echo 'echo $1' >> $SUB_SCRIPT
chmod +x $SUB_SCRIPT
if [[ $1 == "--source" ]]; then
  for X in $(seq 100); do
    MODE=$(source $SUB_SCRIPT "source on")
  done
else
  for X in $(seq 100); do
    MODE=$($SUB_SCRIPT "source off")
  done
fi
echo $MODE
rm $SUB_SCRIPT

Output:

~ ❯❯❯ time ./test.sh
source off
./test.sh  0.15s user 0.16s system 87% cpu 0.360 total

~ ❯❯❯ time ./test.sh --source
source on
./test.sh --source  0.05s user 0.06s system 95% cpu 0.114 total

* For example when virus or security tools are running on a device it might take an extra 100ms to exec a new process.


chmod a+x /path/to/file-to-be-executed

That was the only thing I needed. Once the script to be executed is made executable like this, you (at least in my case) don't need any other extra operation like sh or ./ while you are calling the script.

Thanks to the comment of @Nathan Lilienthal


Use backticks.

$ ./script-that-consumes-argument.sh `sh script-that-produces-argument.sh`

Then fetch the output of the producer script as an argument on the consumer script.


There are some problems to import functions from other file.
First: You needn't to do this file executable. Better not to do so! just add

. file

to import all functions. And all of them will be as if they are defined in your file.
Second: You may be define the function with the same name. It will be overwritten. It's bad. You may declare like that

declare -f new_function_name=old_function_name 

and only after that do import. So you may call old function by new name.
Third: You may import only full list of functions defined in file. If some not needed you may unset them. But if you rewrite your functions after unset they will be lost. But if you set reference to it as described above you may restore after unset with the same name.
Finally In common procedure of import is dangerous and not so simple. Be careful! You may write script to do this more easier and safe. If you use only part of functions(not all) better split them in different files. Unfortunately this technique not made well in bash. In python for example and some other script languages it's easy and safe. Possible to make partial import only needed functions with its own names. We all want that in next bush versions will be done the same functionality. But now We must write many additional cod so as to do what you want.

참고URL : https://stackoverflow.com/questions/8352851/how-to-call-shell-script-from-another-shell-script

반응형