LoginSignup
3
1

More than 5 years have passed since last update.

'. test.sh'と'sh test.sh'と'./test.sh'の違い

Last updated at Posted at 2019-03-19

getoptsを関数(function)の中で使うに関連して。

  • . test.sh (= source test.sh)
  • sh test.sh
  • ./test.sh

とシェルスクリプトを実行する方法は複数あるが、
状況によっては異なる結果になる。

sh test.sh ./test.sh に違いがあるかなどよくわかっていないところが多いので追って詳細について記載したい。

TL;DR

  • . test.sh で実行した場合
    • 変数はシェル変数として扱われ、使用する変数がシェル変数として設定済みであれば影響を受ける
    • シェル変数が設定されていない状態で実行した後には、シェル変数が設定された状態になる
  • sh test.sh ./test.sh で実行した場合
    • localで宣言していなくても変数はシェル変数として扱われない

検証に使用したコード

getoptsを関数(function)の中で使う
の冒頭に記載のコード(local宣言していないほう)を
test.shとして作成し実行権限をつける

検証結果

実行結果
$ sh test.sh -i 16 -o 10 A
10
$ sh test.sh -i 16 -o 8 A
12
$ sh test.sh -i 8 -o 10 16
14
$ set | egrep "^OPT|^input|^output"
$ ./test.sh -i 16 -o 10 A
10
$ ./test.sh -i 16 -o 8 A
12
$ ./test.sh -i 8 -o 10 16
14
$ set | egrep "^OPT|^input|^output"
$ . test.sh -i 16 -o 10 A
10
$ . test.sh -i 16 -o 8 A
10
$ . test.sh -i 8 -o 10 16
22
$ set | egrep "^OPT|^input|^output"
OPT='?'
OPTERR=1
OPTIND=5
input=16
output=10
3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1