2009-04-30
Bash scripts and directory names with spaces
As a rule I avoid directory names with spaces, but from time to time you have to deal with these oddities in your bash scripts. Here is a quick script that demonstrates how to work around this problem...
To test, create a directory like "/tmp/some dir". Change into this directory and run the script. You should see something like this:
As you can see, it breaks at line 3. Here is the script:
The trick lies in line 9 - using quotes :-)
To test, create a directory like "/tmp/some dir". Change into this directory and run the script. You should see something like this:
1 $ /tmp/test.sh
2 Attempting to go back to '/tmp/some dir'
3 /tmp/test.sh: line 6: cd: /tmp/some: No such file or directory
4 /tmp/some dir
5 DONE
As you can see, it breaks at line 3. Here is the script:
1 #!/bin/bash
2
3 HERE=`pwd`
4 cd /tmp
5 echo "Attempting to go back to '$HERE'"
6 cd $HERE
7 if [ $? -gt 0 ]
8 then
9 cd "$HERE"
10 if [ $? -gt 0 ]
11 then
12 echo "FAILED"
13 fi
14 fi
15 pwd
16 echo DONE
The trick lies in line 9 - using quotes :-)