Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass command line argument with space in Bash scripts

Let's say there is one script s1, and I need to pass argument $1 with value foo bar, with space in it. This can be done

./s1 "foo bar"

however, when I want to run the above command in another script (say s2), how should I put it? If I put it as above, foo bar will be interpreted as two arguments (to s1) rather than one.

like image 482
Richard Avatar asked Aug 08 '12 17:08

Richard


People also ask

How do you pass a space in command line arguments?

Note : You pass all the command line arguments separated by a space, but if argument itself has a space then you can pass such arguments by putting them inside double quotes “” or single quotes ”.

How do you put a space between lines in shell script?

The G command appends a newline and the hold space to the end of the pattern space. Since, by default, the hold space is empty, this has the effect of just adding an extra newline at the end of each line. The prefix $! tells sed to do this on all lines except the last one.

How do you represent a space in bash?

To cd to a directory with spaces in the name, in Bash, you need to add a backslash ( \ ) before the space. In other words, you need to escape the space.

How do you handle a space in bash?

Filename with Spaces in Bash A simple method will be to rename the file that you are trying to access and remove spaces. Some other methods are using single or double quotations on the file name with spaces or using escape (\) symbol right before the space.


2 Answers

You can try quoting $1:

./s2 "$1"
like image 188
cnicutar Avatar answered Oct 16 '22 11:10

cnicutar


Use single quotes.

./script 'this is a line'

To consider variable substitutions use double quotes

./script "this is a line"

like image 1
phoxis Avatar answered Oct 16 '22 13:10

phoxis