16
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

シェルスクリプト $0 パラメータ

Last updated at Posted at 2019-12-13

$0 パラメータ には、起動中のシェルスクリプト名がセットされています。

bash のコンソール上の場合

/bin/bash がセットされています。

example1
$ echo "$0"
/bin/bash
シェルスクリプト内の場合

その実行したシェルスクリプト名がセットされています。

example2.sh
# !/bin/bash
echo "$0"
result2
$ ./example2.sh
./example2.sh
basename コマンドを使ってスクリプト名だけ取り出す

bash のコンソール上の場合

example3
$ basename "$0"
bash

シェルスクリプト内の場合

example4.sh
# !/bin/bash
basename "$0"
result4
$ ./example4.sh
example4.sh
シェルの -c オプション

man bash で調べると、-c オプションに関して以下のような記述があります。

-c   If the -c option is present, then commands are read from the first non-option argument command_string.
If there are arguments after the command_string, the first argument is assigned to $0 and any remaining arguments are assigned to the positional parameters.
The assignment to $0 sets the name of the shell, which is used in warning and error messages.

つまり、以下のように記述すると、$0 に test、$1 に hello がセットされます。

example5
$ /bin/bash -c 'echo "$0"; echo "$1"' test hello
test
hello
16
10
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
16
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?