Mac OS X - Passing pathname with spaces as arguments to bashscript and then issue open Terminal command

StackOverflow https://stackoverflow.com/questions/21496182

Question

Problem Using bash shell on Mac OS X Mavericks

I created a bash script called test.sh that accepts one command line argument:-

$ cat test.sh
#!/bin/bash
open -a Terminal $1

When i execute this script in the following way:-

$ ./test.sh /Users/myusername/Desktop/folderwithoutspaces/

it executes perfectly and launches a new Terminal window in the given folder.

But when i execute this script in the following way:-

$ ./test.sh /Users/myusername/Desktop/folder\ withspaces/

it fails to open a new Terminal window and shows the following error message:-

The files /Users/myusername/Desktop/folder and /Users/myusername/Desktop/withspaces do not exist.

I tried all these possible ways but wasn't successful at any:-

$ ./test.sh "/Users/myusername/Desktop/folder\ withspaces/"
$ ./test.sh "/Users/myusername/Desktop/folder withspaces/"
$ ./test.sh '/Users/myusername/Desktop/folder\ withspaces/'
$ ./test.sh '/Users/myusername/Desktop/folder withspaces/'
$ ./test.sh /Users/myusername/Desktop/folder\ withspaces/
Was it helpful?

Solution

When you use the variable with quoting, it gets split based on IFS (which includes a whitespace by default). The solution is to quote the variable. Instead of saying:

open -a Terminal $1

say:

open -a Terminal "$1"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top