How to accommodate spaces in a variable in a bash shell script?

9.1k views Asked by At

Hopefully this should be a simple one... Here is my test.sh file:

#!/bin/bash
patch_file="/home/my dir/vtk.patch"
cmd="svn up \"$patch_file\""
$cmd

Note the space in "my dir". When I execute it,

$ ./test.sh 
Skipped '"/home/my'
Skipped 'dir/vtk.patch"'

I have no idea how to accommodate the space in the variable and still execute the command. But executing this the following on the bash shell works without problem.

$ svn up "/home/my dir/vtk.patch"   #WORKS!!!

Any suggestions will be greatly appreciated! I am using the bash from cygwin on windows.

2

There are 2 answers

3
Kevin Beck On BEST ANSWER

Use eval $cmd, instead of plain $cmd

2
Dave On

Did you try escaping the space?
As a rule UNIX shells don't like non-standard characters in file names or folder names. The normal way of handling this is to escape the offending character. Try:

patch_file="/home/my\ dir/vtk.patch"

Note the backslash.