Search code examples
linuxbashshellls

"ls" works in cmd line but not in script for directories with space in their names


I am a beginner in bash scripting and I am trying to write a script which has as variables directory names, and who uses those variable values to run simple bash commands such as "ls" and "cd". It works perfectly fine when the directory has a "normal" name, for example

testfolder/folder01

But fails miserably when the directory has spaces and parenthesis in their names, which happens for example when you do a copy a subdirectory and paste in the same directory containing the subdirectory. The problem can be seen in this script:

[boblacerda@localhost MyScripts]$ cat test.sh
#!/bin/bash
VARDIR="testfolder/folder01"
ls $VARDIR
VARDIR="testfolder/folder01\ \(copy\)"
ls $VARDIR
[boblacerda@localhost MyScripts]$

This is the output of the script in debugging mode:

[boblacerda@localhost MyScripts]$ bash -x test.sh
+ VARDIR=testfolder/folder01
+ ls testfolder/folder01
testefile01  testefile02
+ VARDIR='testfolder/folder01\ \(copy\)'
+ ls 'testfolder/folder01\' '\(copy\)'
ls: cannot access testfolder/folder01\: No such file or directory
ls: cannot access \(copy\): No such file or directory
+ exit
[boblacerda@localhost MyScripts]$

As you see the first part, who uses a directory with a "normal" name works, but the second part, who uses a directory with spaces and parenthesis in its name, fails. The problem persists if I quote VARDIR in the ls command, i.e., if I use ls like this

ls "$VARDIR"

The output in this case is like this:

[boblacerda@localhost MyScripts]$ bash -x test.sh
+ VARDIR=testfolder/folder01
+ ls testfolder/folder01
testefile01  testefile02
+ VARDIR='testfolder/folder01\ \(copy\)'
+ ls 'testfolder/folder01\ \(copy\)'
ls: cannot access testfolder/folder01\ \(copy\): No such file or directory
+ exit
[boblacerda@localhost MyScripts]$

A final remark to add that the command

ls testfolder/folder01\ \(copy\)

works fine in the cmd as shown below:

[boblacerda@localhost MyScripts]$ls testfolder/folder01\ \(copy\)
testefile01  testefile02
[boblacerda@localhost MyScripts]$

Thank you all for the attention.


Solution

  • Try:

    ls "$VARDIR"
    

    The double quotes will preserve the space, no need for backslashes.