Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over arguments in a Bash script

I have a complex command that I'd like to make a shell/bash script of. I can write it in terms of $1 easily:

foo $1 args -o $1.ext 

I want to be able to pass multiple input names to the script. What's the right way to do it?

And, of course, I want to handle filenames with spaces in them.

like image 262
Thelema Avatar asked Nov 01 '08 18:11

Thelema


1 Answers

Use "$@" to represent all the arguments:

for var in "$@" do     echo "$var" done 

This will iterate over each argument and print it out on a separate line. $@ behaves like $* except that when quoted the arguments are broken up properly if there are spaces in them:

sh test.sh 1 2 '3 4' 1 2 3 4 
like image 109
Robert Gamble Avatar answered Oct 20 '22 05:10

Robert Gamble