0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

位置パラーメータ

Posted at

位置パラーメータとは

シェルスクリプト内からコマンドライン引数を扱うためのシェル変数。

# test.shの中身
#!/bin/bash
echo $1 $2 $3

test.sh hello world !

# $1 に hello
# $2 に world
# $3 に !
# が渡される

=> hello world !

$0

$0は位置パラメータではなく特殊パラメータの一つ。シェルスクリプトを実行したときのシェルスクリプト名が渡される。

# test.shの中身
#!/bin/bash

echo "Execute $0 !"
/
./tesh.sh

=> Execute ./test.sh !

ワイルドカード

コマンドライン引数に 「*」 を渡した場合、現在のディレクトリのファイル、ディレクトリが展開され引数として渡される。

# カレントディレクトリにfile_1とfile_2がある場合
ls

=> file_1 file_2

# test.shの中身
#!/bin/bash

echo $1
echo $2

# 「*」に対してカレントディレクトリの内容がそれぞれ位置パラメータに設定される
./test.sh *

=> file_1
=> file_2

引数の数を参照する

「$#」を利用すると渡されたコマンドライン引数がわかる。

# test.shの中身
#!/bin/bash

echo $#

./test.sh a b c d e f g

=> 7

コマンドライン引数をまとめて参照する

「#@」「#*」を使うと、シェルスクリプトに渡されたコマンドライン引数をまとめて扱うことができる。

# test.shの中身
#!/bin/bash

echo $@
echo $*

./test.sh a b c d e f g

=> a b c d e f g
=> a b c d e f g

「#@」「$*」の違うところは「echo "#@"(あるいは「#*」)」とダブルクォートで囲った場合

  • 「"#@"」を利用した場合
    各位置パラメータに渡された引数が、ダブルクォートで分割される。そのためシェルスクリプト内でコマンドにコマンドライン引数をまとめて渡すことができる。
  • 「"#*"」を利用した場合
    全ての位置パラメータに渡されたコマンドライン引数が一つのダブルクォートに囲まれ一つの文字列となる。
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?