以下の例は、第一引数、第二引数を表示、全ての引数を表示、引数の数を表示しています。
$ cat -n testarg 1 #! /bin/bash 2 echo "1st $1, 2nd $2" 3 echo "all $*" 4 echo "number of args $#"解説
$ testarg one two three four 1st one, 2nd two all one two three four number of args 4
変数名 | 意味 |
---|---|
$0 | 実行中のスクリプト・ファイル名 |
$* | 全ての引き数。1つの文字列として扱う。 |
$# | 引数の数。 |
$n | 個々の引数。1番目であれば $1, 2番目は $2 の順となります。 nが二桁以上となる場合は、中括弧で結びます。例) ${100} |
$ ls c* calc check chfm chkpsent chx clean cntr $ testarg c* 1st calc, 2nd check all calc check chfm chkpsent chx clean cntr number of args 7
$ ls -ld /tmp drwxrwxrwt 4 root root 4096 Sep 24 10:32 /tmp $ echo $? 0 $ ls -ld /tmp/detarame ls: /tmp/detarame: No such file or directory $ echo $? 1この値を「戻り値」といい、UNIX では正常終了時に 0 を返すという慣習があります。
例えば… 正常に終了したとき exit 0 エラーがあった場合 exit 2エラー値は特に決まっていませんが、UNIX(Linux) の OS としての値は、C言語用の インクルードファイルとして /usr/include/errno.h に定義されています。
#define EPERM 1 /* Operation not permitted */ #define ENOENT 2 /* No such file or directory */ #define ESRCH 3 /* No such process */ #define EINTR 4 /* Interrupted system call */ #define EIO 5 /* I/O error */ #define ENXIO 6 /* No such device or address */ : 省略