Bash: for loop and positional parameters ($*, [email protected])

Time:2021-8-1

Word splitting

If the variable is not in double quotation marks, the shell will segment the variable after parameter expansion, command replacement and arithmetic expansion, such as:

$ echo a   b  c      d
a b c d

Shell will$IFSEach character of is used as a separator if$IFSIf it is unset, it has a default value<space><tab><newline>

When word segmentation, first ignore the blank character at the first place of the variable<space><tab><newline>Then separate the words.

judge$IFSWhether to unset the method.

//File test
#!/usr/bin/bash
if [ -v IFS ];then
  echo ==$IFS=$IFS==
else
  echo ==$IFS is unset==
fi

$ ./test
==$IFS= ==

$* and in the for [email protected]

$*And[email protected]Can represent all position parameters.

  • Not in double quotation marks: both are used in the same way, and word segmentation will be performed.

    //File test
    #!/usr/bin/bash
    echo '==$*=='
    for name in $*
    do
    echo $name
    done
    
    echo '[email protected]=='
    for name in [email protected]
    do
    echo $name
    done
    
    $ ./test a  s  d fff
    ==$*==
    a
    s
    d
    fff
    [email protected]==
    a
    s
    d
    fff
  • In double quotation marks:

$*Will first participle, and then$IFSThe first character of is a separator, which is combined into a string;"$*"amount to"$1c$2c…"cexpress$IFSThe first character of the.

[email protected]It can also segment words, but it will not be combined into a string;
"[email protected]"amount to"$1" "$2"…, it’s the same as throwing it out without double quotes.

//File test
#!/usr/bin/bash
echo '==$*=='
for name in "$*"
do
  echo $name
done

echo '[email protected]=='
for name in "[email protected]"
do
  echo $name
done

$ ./test a  s  d fff
==$*==
a s d fff
[email protected]==
a
s
d
fff

reference resources

Recommended Today

Java Engineer Interview Questions

The content covers: Java, mybatis, zookeeper, Dubbo, elasticsearch, memcached, redis, mysql, spring, spring boot, springcloud, rabbitmq, Kafka, Linux, etcMybatis interview questions1. What is mybatis?1. Mybatis is a semi ORM (object relational mapping) framework. It encapsulates JDBC internally. During development, you only need to pay attention to the SQL statement itself, and you don’t need to […]