问答详情
源自:2-5 位置参数变量

$*不用双引号的话循环输出多个

老师好哈,我写的for区分$*下面这样也循环多次输出呢,为啥啊

#!/bin/bash

#for区分$*和$@

    for i in $*   #区别在这里,&*没有双引号,有了双引号就循环一次,没有则会多次      

    do

            echo "\$*:$i"

    done

    for j in $@         

    do

            echo "\$@:$j"

    done

  //运行结果如下

$*:11

$*:22

$*:33

$*:44

$@:11

$@:22

$@:33

$@:44


提问者:苏小闲 2016-01-06 22:27

个回答

  • jxm080511321
    2016-01-07 02:04:19

    #!/bin/bash
    set 'apple pie' pears peaches
    for i in $* /*单引号被去掉,循环单个字符输出*/
    do echo $i

    done

    [root@luozhonghua Ex_14.02-14.31]# sh 14-14-1
    apple
    pie
    pears
    peaches

    --------------------------------------------------------------

    #!/bin/bash
    set 'apple pie' pears peaches
    for i in "$*" /*单引号被去掉,但当作字符串一次输出*/
    do echo $i
    done

    [root@luozhonghua Ex_14.02-14.31]# sh 14-14-2
    apple pie pears peaches
    [root@luozhonghua Ex_14.02-14.31]#

    -----------------------------------------------------------------



    #!/bin/bash
    set 'apple pie' pears peaches
    for i in $@ /*单引号被去掉,循环单个字符输出*/
    do echo $i 
    done
    [root@luozhonghua Ex_14.02-14.31]# sh 14-14-3
    apple
    pie
    pears
    peaches

    -----------------------------------------------------------------

    #!/bin/bash
    set 'apple pie' pears peaches
    for i in "$@" /*每个位置参数都将当成一个加引号的字符串:"apple pie","pears ","peaches"*/
    do echo $i
    done
    [root@luozhonghua Ex_14.02-14.31]# sh 14-14-4
    apple pie
    pears
    peaches