次の問題があります。私のシェルスクリプトには、次の内容が含まれています。
mydir=''
# config load
source $mydir/config.sh
.... execute various commands
私のスクリプトは私のユーザーディレクトリにあります。/home/bob/script.sh
私が/home/bob
ディレクトリ内にいて実行すると、./script.sh
すべてがうまくいきます。
外部にあり、絶対パスを使用しようとすると、/home/bob/script.sh
config.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
。