Programing

다른 쉘 스크립트에서 쉘 스크립트의 함수를 호출 할 수 있습니까?

crosscheck 2020. 11. 4. 07:42
반응형

다른 쉘 스크립트에서 쉘 스크립트의 함수를 호출 할 수 있습니까?


2 개의 셸 스크립트가 있습니다.

두 번째 셸 스크립트에는 second.sh 함수가 포함되어 있습니다.

func1 
func2

first.sh는 일부 매개 변수를 사용하여 두 번째 셸 스크립트를 호출하고 해당 함수에 특정한 다른 매개 변수와 함께 func1 및 func2를 호출합니다.

다음은 제가 말하는 것의 예입니다.

second.sh

val1=`echo $1`
val2=`echo $2`

function func1 {

fun=`echo $1`
book=`echo $2`

}

function func2 {

fun2=`echo $1`
book2=`echo $2`


}

first.sh

second.sh cricket football

func1 love horror
func2 ball mystery

어떻게 할 수 있습니까?


다음 second.sh과 같이 스크립트를 리팩터링하십시오 .

function func1 {
   fun=$1
   book=$2
   printf "fun=%s,book=%s\n" "${fun}" "${book}"
}

function func2 {
   fun2=$1
   book2=$2
   printf "fun2=%s,book2=%s\n" "${fun2}" "${book2}"
}

그리고 다음 first.sh과 같이 스크립트에서 이러한 함수를 호출 합니다.

source ./second.sh
func1 love horror
func2 ball mystery

산출:

fun=love,book=horror
fun2=ball,book2=mystery

다른 쉘 스크립트에서 직접 함수를 호출 할 수 없습니다.

함수 정의를 별도의 파일로 이동 한 다음 다음 .과 같이 명령을 사용하여 스크립트로로드 할 수 있습니다 .

. /path/to/functions.sh

functions.sh시점에서 콘텐츠가 실제로 파일에있는 것처럼 해석 됩니다. 이것은 쉘 함수의 공유 라이브러리를 구현하기위한 일반적인 메커니즘입니다.


문제

현재 받아 들여지는 대답은 중요한 조건에서만 작동합니다. 주어진...

/foo/bar/first.sh:

function func1 {  
   echo "Hello $1"
}

/foo/bar/second.sh:

#!/bin/bash

source ./first.sh
func1 World

이것은이 first.sh있는 동일한 디렉토리 내 에서이 실행되는 경우에만 작동합니다 first.sh. 즉. 쉘의 현재 작업 경로가 /foo이면 명령 실행 시도

cd /foo
./bar/second.sh

오류를 인쇄합니다.

/foo/bar/second.sh: line 4: func1: command not found

이는 source ./first.sh스크립트의 경로가 아니라 현재 작업 경로에 상대적 이기 때문 입니다. 따라서 한 가지 해결책은 서브 쉘을 활용하고

(cd /foo/bar; ./second.sh)

보다 일반적인 솔루션

주어진...

/foo/bar/first.sh:

function func1 {  
   echo "Hello $1"
}

/foo/bar/second.sh:

#!/bin/bash

source $(dirname "$0")/first.sh

func1 World

그때

cd /foo
./bar/second.sh

인쇄물

Hello World

작동 원리

  • $0 실행 된 스크립트의 상대 또는 절대 경로를 반환합니다.
  • dirname $ 0 스크립트가있는 디렉토리의 상대 경로를 반환합니다.
  • $( dirname "$0" ) the dirname "$0" command returns relative path to directory of executed script, which is then used as argument for source command
  • in "second.sh", /first.sh just appends the name of imported shell script
  • source loads content of specified file into current shell

If you define

    #!/bin/bash
        fun1(){
          echo "Fun1 from file1 $1"
        }
fun1 Hello
. file2 
fun1 Hello
exit 0

in file1(chmod 750 file1) and file2

   fun1(){
      echo "Fun1 from file2 $1"
    }
    fun2(){
      echo "Fun1 from file1 $1"
    }

and run ./file2 you'll get Fun1 from file1 Hello Fun1 from file2 Hello Surprise!!! You overwrite fun1 in file1 with fun1 from file2... So as not to do so you must

declare -f pr_fun1=$fun1
. file2
unset -f fun1
fun1=$pr_fun1
unset -f pr_fun1
fun1 Hello

it's save your previous definition for fun1 and restore it with the previous name deleting not needed imported one. Every time you import functions from another file you may remember two aspects:

  1. you may overwrite existing ones with the same names(if that the thing you want you must preserve them as described above)
  2. import all content of import file(functions and global variables too) Be careful! It's dangerous procedure

#vi function.sh

#!/bin/bash
f1() {
    echo "Hello $name"
}

f2() {
    echo "Enter your name: "
    read name
    f1
}
f2

#sh function.sh

Here function f2 will call function f1

참고URL : https://stackoverflow.com/questions/10822790/can-i-call-a-function-of-a-shell-script-from-another-shell-script

반응형