Sign up ×
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 would like to write a bash script with unknown amount of arguments.

How can I walk through these arguments and do something with them?

A wrong attempt would look like this:

for i in $args; do 
    echo $i
share|improve this question

2 Answers 2

up vote 10 down vote accepted

There's a special syntax for this:

for i do
  echo "$i"

More generally, the list of parameters of the current script or function is available through the special variable $@.

for i in "$@"; do
  echo "$i"

Note that you need the double quotes around $@, otherwise the parameters undergo wildcard expansion and field splitting. "$@" is magic: despite the double quotes, it expands into as many fields as there are parameters.

print_arguments () {
  for i in "$@"; do echo "$i"; done
print_arguments 'hello world' '*' 'special   !\characters'    # prints 3 lines
print_arguments ''                                            # prints one empty line
print_arguments                                               # prints nothing
share|improve this answer
#! /usr/bin/env bash
for f in "$@"; do
  echo "$f"

You should quote $@ because it is possible for arguments to contain spaces (or newlines, etc.) if you quote them, or escape them with a \. For example:

./myscript one 'two three'

That's two arguments rather than three, due to the quotes. If you don't quote $@, those arguments will be broken up within the script.

share|improve this answer
There's a shorthand for this for f; do ... – glenn jackman Jun 13 '13 at 23:36

Your Answer


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.