How to pass argument with spaces to a shell script function?
Solution 1
You should just quote the second argument.
myfunc(){
echo "$1"
echo "$2"
echo "$3"
}
myfunc hi "hello guys" bye
Solution 2
It is the same as calling anything (a shell script, a C program, a python program, …) from a shell
If calling from any Unix shell, and the parameter has spaces, then you need to quote it.
sh my-shell-script hi "hello guys" bye
You can also use single quotes, these are more powerful. They stop the shell from interpreting anything ($
, !
, \
, *
, "
, etc, except '
)
sh my-shell-script hi 'hello guys' bye
You should also quote every variable used within the function/script.
Note that in your example the arguments are falling apart before they get to the function (as they are passed to the script).
#!/bin/sh
my_procedure{
echo "$1"
echo "$2"
echo "$3"
}
my_procedure("$@")
There is no way to do it automatically, in the script, as there is no way for the script to know which spaces are which (which words are together).
Related videos on Youtube
Klam
Updated on September 18, 2022Comments
-
Klam almost 2 years
I'm writing a form and I seem to be missing my params[:id] when it gets to the Content Controller.
This is my routes.rb:
match '/site/content/myaction/:id', :to => 'contents#myaction'
The form is "myaction" which is in a partial _edit.html.erb:
<%= form_tag :action => 'myaction' do %> <input id="old_id" name="myaction_name" type="text" /> <%= submit_tag 'Submit' %> <% end %>
before I submit the form i'm at:
/site/content/edit/:id/
after i hit submit and i'm at the error page i'm at:/site/content/myaction/
It gets to myaction in content controller but i get the error that id is null... and here are the params:
{"utf8"=>"✓", "old_id"=>"2", "commit"=>"Submit", "id"=>nil}
What I am missing? it seems that maybe it's not picking my route? how else is it re-directing then...
Any suggestion is much appreciated.
-
AnkitG over 11 yearshave you defined myaction as 'POST' in routes?
-
Klam over 11 yearsI just tried it... i commented out the match in my rules and replaced it with: post "site/content/myaction/:id", :to => 'contents#myaction'. Same result
-
Stéphane Chazelas almost 10 years@Gnouc. Not in
dash
. Inyash
yes. Thoughzsh
also acceptsksh
's function definition syntax,function() echo x; function
will work inzsh
. So the only shells where that is a problem areksh
,bash
andyash
. -
cuonglm almost 10 years@StéphaneChazelas: Oh, I retry and it works in
zsh
, butdash
doesn't.
-
-
Nathan B about 6 yearsAnd if the parameter has " in it? We need to encode it?
-
Bruno over 5 yearsEscape it.
\"
-
Sam over 3 yearsWhat if 'hello guys' is stored in a variable?
-
ctrl-alt-delor over 3 years@Jacob "You should also quote every variable used within the function/script." (extracted from answer).