Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I want to use my script on many files sometimes.

I used this for the purpose:

for etminput in $1
do
    #process
done

But this just gives the first input. How can I do the process on every wildcard matches?

share|improve this question

2 Answers 2

up vote 9 down vote accepted

If you want to loop over all the arguments to your script, in any Bourne like shell, it's:

for i do
  something with "$i"
done

You could also do:

for i in "$@"; do
  something with "$i"
done

but it's longer and not as portable (though is for modern shells).

Note that:

for i; do
  something with "$i"
done

is neither Bourne nor POSIX so should be avoided (though it works in many shells)


For completeness, in non-Bourne shells:

csh/tcsh

@ i = 1
while ($i <= $#argv)
  something with $argv[$i]:q
  @ i++
end

You cannot use:

foreach i ($argv:q)
  something with $i:q
end

because that skips empty arguments

rc/akanga

for (i) something with $i

(rc generally is what shells should be like).

es

for (i=$*) something with $i

(es is rc on steroids).

fish

for i in $argv
  something with $i
end

zsh

Though it will accept the Bourne syntax, it also supports shorter ones like:

for i ("$@") something with "$i"
share|improve this answer
#!/bin/bash

n=1
echo "$0 got $# args..."
while [ $# -gt 0 ] ;do
  echo "$n: $1"
  shift
  n=$(( $n + 1 ))
done

Alternatively, look up 'Listing arguments with $* and $@'
in http://www.tldp.org/LDP/abs/html/abs-guide.html
which will elaborate on many aspects of these.

share|improve this answer

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.