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.

This question already has an answer here:

I'm trying to pass multiple argument to a function, but one of them is consist of two words and I want shell function to deal with it as one arg:

args=("$@")
function(){
 echo ${args[0]}
 echo ${args[1]}
 echo ${args[2]}
}

when I call this command sh shell hi hello guys bye

I get this

hi

hello

guys

But what I really want is:

hi 
hello guys
bye
share|improve this question

marked as duplicate by Gilles Aug 24 '14 at 23:38

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
You shouldn't use function as a name of a function. It's a keyword in ksh, and some bourne-shell like bash, zsh, dash. –  cuonglm Aug 23 '14 at 18:31
    
@Gnouc. Not in dash. In yash yes. Though zsh also accepts ksh's function definition syntax, function() echo x; function will work in zsh. So the only shells where that is a problem are ksh, bash and yash. –  Stéphane Chazelas Aug 23 '14 at 20:05
    
@StéphaneChazelas: Oh, I retry and it works in zsh, but dash doesn't. –  cuonglm Aug 23 '14 at 20:13

2 Answers 2

up vote 3 down vote accepted

You should just quote the second argument.

myfunc(){
        echo "$1"
        echo "$2"
        echo "$3"
}

myfunc hi "hello guys" bye
share|improve this answer

If called from any Unix shell, then you need to quote it.

sh shell hi "hello guys" bye

There is no way to do it in the script, at there is no way for the script to know which spaces are which (which words are together).

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.