スクリプトの現在のディレクトリを取得します(相対パスなしでファイルを含め、どこからでもスクリプトを実行できます)。

スクリプトの現在のディレクトリを取得します(相対パスなしでファイルを含め、どこからでもスクリプトを実行できます)。

次の問題があります。私のシェルスクリプトには、次の内容が含まれています。

mydir=''

# config load
source $mydir/config.sh

.... execute various commands

私のスクリプトは私のユーザーディレクトリにあります。/home/bob/script.sh

私が/home/bobディレクトリ内にいて実行すると、./script.shすべてがうまくいきます。

外部にあり、絶対パスを使用しようとすると、/home/bob/script.shconfig.shファイルが正しく呼び出されません。

$mydir各パスでスクリプトを簡単に実行するには、どの値を割り当てる必要がありますか?

mydir=$(which command?)

PS:ボーナスとしてスクリプトディレクトリが$ PATH内にある場合は、代替手段を提供してください。

ベストアンサー1

この$0変数にはスクリプトパスが含まれています。

$ cat ~/bin/foo.sh
#!/bin/sh
echo $0

$ ./bin/foo.sh
./bin/foo.sh

$ foo.sh
/home/terdon/bin/foo.sh

$ cd ~/bin
$ foo.sh
./foo.sh

ご覧のとおり、出力は呼び出し方法によって異なりますが、常にスクリプトの実行方法に関連するスクリプトパスを返します。だからあなたはこれを行うことができます:

## Set mydir to the directory containing the script
## The ${var%pattern} format will remove the shortest match of
## pattern from the end of the string. Here, it will remove the
## script's name,. leaving only the directory. 
mydir="${0%/*}"

# config load
source "$mydir"/config.sh

ディレクトリがあなたのディレクトリにある場合、$PATH状況はより簡単になります。実行できますsource config.sh。デフォルトでは、sourceディレクトリからファイルを検索し、見つかった$PATH最初のファイルをインポートします。

$ 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.

あなたのコンテンツが一意であると確信したり、少なくともでconfig.sh最初に見つかったコンテンツであれば、$PATHそのコンテンツを入手できます。ただし、この方法を使用するのではなく、最初の方法に固執することをお勧めします。いつ他の人がconfig.shあなたのために現れるのかわかりません$PATH

おすすめ記事