bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: How to supply a string with space in it as parameter to a function?


From: Chris F.A. Johnson
Subject: Re: How to supply a string with space in it as parameter to a function?
Date: Wed, 23 Jun 2010 18:43:10 -0400 (EDT)
User-agent: Alpine 2.00 (LMD 1167 2008-08-23)

On Wed, 23 Jun 2010, Peng Yu wrote:

> Hi,
> 
> According to man bash, I thought that $@ instead of $* can help me
> pass a string with space as a parameter. But it is not. Would you
> please show me how to print 'b c' as a single argument in the
> following code?

   Always quote variable references unless you have a good reason not
   to.
 
> #!/usr/bin/env bash
> 
> function f {
> #for i in $*;
> for i in $@;
> do
>   echo $i
> done
> }

for i in "$@"  ## note the quotes
do
  echo "$i"  ## better is: printf "%s\n" "$i"
done

   Or, without a loop:

printf "%s\n" "$@"

> f a 'b c' d e f g
> 
> 
> $ ./main.sh
> a
> b
> c
> d
> e
> f
> g
> 
> 

-- 
   Chris F.A. Johnson, <http://cfajohnson.com>
   Author:
   Pro Bash Programming: Scripting the GNU/Linux Shell (2009, Apress)
   Shell Scripting Recipes: A Problem-Solution Approach (2005, Apress)



reply via email to

[Prev in Thread] Current Thread [Next in Thread]