LoginSignup
7

More than 5 years have passed since last update.

posted at

updated at

最後のコマンドライン引数を取得する

(コメント反映させました。ありがとうございました!)
シェルスクリプトでコマンドライン引数を取得するには

last_arg.sh
#!/bin/bash

echo "Number of arg: $#"
echo "Last arg: ${@:$#:1}"
# POSIX shやkshの場合は以下
# echo "Last arg: $(eval echo '$'{$#})" 

実行例

$ ./last_arg.sh  a1 b2 c3 d4 e5
Number of arg: 5
Last arg: e5

$ ./last_arg.sh  a1 b2 c3 d4 e5 f6 g7 h8 i9 j10 k11
Number of arg: 11
Last arg: k11

evalを使う方は、引数なしで実行した場合$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
What you can do with signing up
7