Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

Is there any method to iterate the passed arguments in a bash script? This answer from my question shows me how to use each argument, but I want to iterate them because the number of arguments is variable.

I tried something like:

for i in {1..10}
do
    if [[ -f "$($i)" ]]
    then
        echo "$($i) is a file"
    elif [[ -d "$($i)" ]]
    then
        echo "$($i) is a directory"
    else
        echo "$($i) is not a file or directory"
    fi
done

But it give me errors. I tried also to use without success $$i instead of $($i)...

share|improve this question

2 Answers 2

up vote 7 down vote accepted

You should use $@ to refer to all the arguments:

for arg in "$@"
do
    if [[ -f "$arg" ]]
    then
        echo "$arg is a file"
    elif [[ -d "$arg" ]]
    then
        echo "$arg is a directory"
    else
        echo "$arg is not a file or directory"
    fi
done

See also: http://www.tldp.org/LDP/abs/html/internalvariables.html#ARGLIST

share|improve this answer
    
+1 I just want to note the importance of quoting "$@" for arguments that may have spaces because I've seen some people forgetting that and leading to unexpected bugs. –  Carlos Campderrós Mar 4 at 13:54
1  
As a special case for the argument list, you can drop the in part and use just for arg; do .... You can use shift or set before the loop to remove arguments that need special handling (e.g. target directory). –  deltab Mar 4 at 15:42

The use of while + shift seems more versatile to me:

while [ ! "$1" == "" ]; do
    case "$1" in
    "--mode" )
            MODE="$1 $2"
            shift
            ;;
    "--clean" )
            CLEAN="$1"
            ;;
    esac
    shift
done

You can, then pass arguments of variable length of terms. Note that, in case of mode, it does an extra shift, besides the one before the end of the loop.

share|improve this answer
    
if you need to work with options, you may find getopt useful. –  Carlos Campderrós Mar 4 at 13:56
    
If you're going to do this, the condition should be while [ -n "$1" ]. –  Kevin Mar 4 at 16:02

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.