LoginSignup
132
110

More than 1 year has passed since last update.

シェルスクリプトで、ある順番以降の引数を取得する

Last updated at Posted at 2013-04-05

……の前に、前提から。

特定の順番にある引数を取得する

${n}を使います。

test.sh
#!/bin/sh

echo $0
echo $1
echo $2

実行結果:

$ ./test.sh foo bar baz
./test.sh
foo
bar

$0がプログラム名になる。上記の場合、baz$3なので出力されない。

引数を全部取得する

$@を使います。

test.sh
#!/bin/sh

echo $@

実行結果:

$ ./test.sh foo bar baz
foo bar baz

ある順番のもの以降を全部取得する

これが本題です。たとえば、引数の3番目以降を全部取得したい場合。

test.sh
#!/bin/sh

echo ${@:3:($#-2)}

実行結果:

$ ./test.sh 1 2 3 4 5
3 4 5

$#には、引数の数が格納されています。なので、この場合は3番目以降の全部なので、全体の数から、いらない2つを引いているわけです。

てか、↑をやんなくても、3番目以降「全部」なら${@:3}でもよかった。つまり、開始の順番だけでよい。3番〜5番目とかなら「3番目以降の3つ」という意味で ${@:3:3}と書く必要がある。

応用例として、2個の引数のあと、--以降にオプションとして解釈されたくない文字列がある場合、以下のように書けます。

test.sh
#!/bin/sh

echo $1
echo $2
echo ${@:4:($#-2)}

実行結果:

$ ./test.sh hoge fuga -- --foo bar --baz qux
hoge
fuga
--foo bar --baz qux

参考文献

補足

デフォルトのshがdashになっているUbuntu等は、解釈プログラムにbash等を指定する。

#!/bin/bash
132
110
2

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
132
110