0

I have been trying many different ways to loop through the arguments, using different ways with for and while loops, yet it doesn't work. My script should take arguments and answer if they are files, directoies etc.

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

How do I loop though each arguments?

codeforester
  • 39,467
  • 16
  • 112
  • 140
Tomb_Raider_Legend
  • 431
  • 13
  • 29

2 Answers2

2

This is what you want to use:

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

The first time through the loop, $arg becomes the first argument. The next time, it becomes the second argument, etc.

In general, a for loop iterates over whatever items you give it, assigning each item to the variable. For example, if you did

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

Then $x would be "a" the first time through the loop, then "b", then "c", so your output would be:

a
b
c

In the code at the top, instead of using explicit values, we're using "$@" instead, which means "whatever arguments we passed to this script".

Vaughn Cato
  • 63,448
  • 5
  • 82
  • 132
1

while uses a condition, it doesn't iterate a list.

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

To iterate a list, use for:

for file in "$@" ; do
    if [[ -f "$file" ]] ; then
        echo File "$file".
    elif
        ...
    fi
done
choroba
  • 231,213
  • 25
  • 204
  • 289