Special Parameters

範例 ex_001

ex_001.sh

#!/usr/bin/env bash

echo '=============================================='

echo '$@:' $@
echo '$*:' $*

echo '=============================================='

echo '$#:' $#

echo '=============================================='

echo '$0:' $0
echo '$1:' $1
echo '$2:' $2
echo '$3:' $3
echo '$4:' $4
echo '$5:' $5
echo '$6:' $6
echo '$7:' $7
echo '$8:' $8
echo '$9:' $9
echo '${10}:' ${10}
echo '${11}:' ${11}
echo '${12}:' ${12}
echo '${13}:' ${13}
echo '${14}:' ${14}
echo '${15}:' ${15}

echo '=============================================='

執行

$ ./ex_001.sh a b c d e f g h i j k l m n o

顯示

==============================================
$@: a b c d e f g h i j k l m n o
$*: a b c d e f g h i j k l m n o
==============================================
$#: 15
==============================================
$0: ./ex_001.sh
$1: a
$2: b
$3: c
$4: d
$5: e
$6: f
$7: g
$8: h
$9: i
${10}: j
${11}: k
${12}: l
${13}: m
${14}: n
${15}: o
==============================================

文件說明

執行

$ man bash

可以看到下面一段說明

Special Parameters
    The shell treats several parameters specially.  These parameters may only be referenced; assignment to them  is
    not allowed.
    *      Expands  to  the  positional  parameters,  starting  from  one.  When the expansion is not within double
           quotes, each positional parameter expands to a separate word.  In contexts where it is performed,  those
           words  are  subject  to further word splitting and pathname expansion.  When the expansion occurs within
           double quotes, it expands to a single word with the value of each parameter separated by the first char‐
           acter  of  the  IFS  special variable.  That is, "$*" is equivalent to "$1c$2c...", where c is the first
           character of the value of the IFS variable.  If IFS is unset, the parameters are  separated  by  spaces.
           If IFS is null, the parameters are joined without intervening separators.
    @      Expands  to  the  positional  parameters,  starting  from  one.  When the expansion occurs within double
           quotes, each parameter expands to a separate word.  That is, "$@" is equivalent to "$1" "$2" ...  If the
           double-quoted  expansion  occurs  within a word, the expansion of the first parameter is joined with the
           beginning part of the original word, and the expansion of the last parameter is  joined  with  the  last
           part  of  the  original  word.   When  there are no positional parameters, "$@" and $@ expand to nothing
           (i.e., they are removed).
    #      Expands to the number of positional parameters in decimal.