1 Replies - 1096 Views - Last Post: 01 September 2010 - 11:29 AM Rate Topic: -----

#1 Zel2008   User is offline

  • D.I.C Addict

Reputation: 17
  • View blog
  • Posts: 893
  • Joined: 06-January 09

Bash arguments problem

Posted 01 September 2010 - 10:56 AM

Hi everybody,
I cannot for the life of me figure out what I'm doing wrong here, but I cannot get BASH to ignore spaces in arguments passed to a script. With the following script:


for i in $*
echo "${i}"

I have tried:

./myScript Test "This is a test"
./myScript Test 'This is a test'
./myScript Test This\ is\ a\ test

hoping to get:
This is a test

But I keep getting this instead:

I've used spaces in arguments with bash scripts a million times, and one of those three solutions above has always worked. I can't understand why it's not working now. The reason I want to pull the spaced string in whole is so the number of parameters can't possibly go over 9 (this seems to be the BASH limit), then split it into an array (which I can't figure out until I get this).

Would anyone mind letting me know where I'm going wrong? I'd appreciate any help.


EDIT: Hmm, sometimes it seems like the act of posting on here helps me find the right answer. Anyway, the solution is to loop over your bash arguments, shifting them off the end after you use them, like so:

    while [ $# -ne 0 ]; do
        echo "                ${1}"

That way, you don't have to worry about spaces or having more than 9 arguments.

Hope that helps someone!

This post has been edited by Zel2008: 01 September 2010 - 11:21 AM

Is This A Good Question/Topic? 0
  • +

Replies To: Bash arguments problem

#2 JackOfAllTrades   User is offline

  • Saucy!
  • member icon

Reputation: 6246
  • View blog
  • Posts: 24,014
  • Joined: 23-August 08

Re: Bash arguments problem

Posted 01 September 2010 - 11:29 AM

From here: you need to quote the variable in the for, AND you should be using $@, not $*.
#!/usr/bin/env bash                                                             

for i in "$@";
    echo "${i}"

./b.bash Test "This is a test"
This is a test

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1