【问题标题】:Loop through arguments [duplicate]循环参数[重复]
【发布时间】:2015-12-25 15:49:46
【问题描述】:

我一直在尝试许多不同的方式来循环参数,使用不同的方式与 for 和 while 循环,但它不起作用。如果它们是文件、目录等,我的脚本应该接受参数并回答。

while $1 in "$@" ;do

if [ -f $1 ];then
        echo "$1        regular file"

elif [ -d $1 ];then
        echo "$1        directory"

elif [ -f $1 ];then
        echo "$1        excuteable file"

elif [ -h $1 ];then
        echo "$1        symbolic"

else
        echo "$1        Does not exist"
fi

1=$(( $1 + 1 ))

done

如何循环每个参数?

【问题讨论】:

    标签: bash shell loops


    【解决方案1】:

    这是你想要使用的:

    for arg in "$@"; do
        if [ -f $arg ];then
            echo "$arg        regular file"
        elif [ -d $arg ];then
            echo "$arg        directory"
        elif [ -f $arg ];then
            echo "$arg        excuteable file"
        elif [ -h $arg ];then
            echo "$arg        symbolic"
        else
            echo "$arg        Does not exist"
        fi
    done
    

    第一次循环时,$arg 成为第一个参数。下一次,它成为第二个参数,等等。

    一般来说,for 循环会遍历您提供给它的任何项目,并将每个项目分配给变量。例如,如果你这样做了

    for x in a b c; do
        echo $x
    done
    

    那么$x 第一次通过循环时将是“a”,然后是“b”,然后是“c”,所以您的输出将是:

    a
    b
    c
    

    在顶部的代码中,我们没有使用显式值,而是使用"$@",这意味着“我们传递给此脚本的任何参数”。

    【讨论】:

    • 在这种情况下,如何给 arg 赋予 $1 的值? "$@" 中的 "for arg" 是否也将 $1 值设置到 arg 中?
    • @Tomb_Raider_Legend:我已经添加了更多解释。
    【解决方案2】:

    while 使用条件,它不迭代列表。

    while (( $# )); do
        if [[ -f "$1" ]] ; then
            echo File "$1".
        elif 
            ...
        fi
        shift  # Remove the first argument from $@.
    done
    

    要迭代列表,请使用for

    for file in "$@" ; do
        if [[ -f "$file" ]] ; then
            echo File "$file".
        elif
            ...
        fi
    done
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-10
      • 2018-04-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多