views:

48

answers:

3

I need to verify if the args are valid file names, is this the right way to do it? It seems like I made some mistake inline 2, but I don't know where.

for i in ${@}; do           
if [ -f ${i}]; then           
    echo ${i}
else continue
fi
done
A: 

-f checks that ${i} is a regular file.

ennuikiller
+2  A: 

First of all, you need a space before the closing square bracket. And you should quote your variables in case there's a space in a filename.

for i in "${@}"; do 
if [ -f "${i}" ]; then
    echo "${i}"
else continue
fi
done

The "else continue" is unnecessary, unless that's a placeholder for something else you plan to put in place of "continue".

Dennis Williamson
If you're looping over the positional parameters, then you can just say: for i; do ...; done
glenn jackman
+1  A: 

Here is a terse solution, which works even if file names contain spaces:

for i
do
    test -f "$i" && echo "$i"
done

Note that the for statement assumes the command line arguments, there is no need to type more. The test command is a short way of if .. then .. fi

Hai Vu