155

その関数にアクセスできるようにするために、シェルスクリプトに別のシェルスクリプトを含める方法はありますか?

PHP の場合と同様にinclude、関数名を呼び出すだけで含まれている関数を実行するために、他の PHP ファイルでディレクティブを使用できます。

4

5 に答える 5

233

スクリプトの中に入れるだけです:

source FILE

または

. FILE # POSIX compliant

$ LANG=C help source
source: source filename [arguments]
Execute commands from a file in the current shell.

Read and execute commands from FILENAME in the current shell.  The
entries in $PATH are used to find the directory containing FILENAME.
If any ARGUMENTS are supplied, they become the positional parameters
when FILENAME is executed.

Exit Status:
Returns the status of the last command executed in FILENAME; fails if
FILENAME cannot be read.
于 2012-05-30T20:20:14.467 に答える
71

上記の回答は正しいですが、スクリプトを別のフォルダーで実行すると、問題が発生します。

たとえば、a.shb.shが同じフォルダにある場合、a を使用. ./b.shして b を含めます。

たとえば、フォルダからスクリプトを実行するとxx/xx/xx/a.sh、ファイルb.shが見つかりません: ./b.sh: No such file or directory.

だから私は使う

. $(dirname "$0")/b.sh
于 2016-12-22T09:50:50.597 に答える
34

はい、ソースまたは短い形式を使用して.ください:

. other_script.sh
于 2012-05-30T20:20:29.863 に答える