Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell script issue with filenames containing spaces

I understand that one technique for dealing with spaces in filenames is to enclose the file name with single quotes: "'".

Why is it that the following code called, "echo.sh" works on a directory containing filenames with spaces, but the program "ls.sh" does Not work, where the only difference is 'echo' replaced with 'ls'?

echo.sh

#!/bin/sh
for f in *
do
echo "'$f'"
done

Produces:
'a b c'
'd e f'
'echo.sh'
'ls.sh'

But, "ls.sh" fails:

#!/bin/sh
for f in *
do
ls "'$f'"
done

Produces:
ls: cannot access 'a b c': No such file or directory
ls: cannot access 'd e f': No such file or directory
ls: cannot access 'echo.sh': No such file or directory
ls: cannot access 'ls.sh': No such file or directory

like image 423
tgoneil Avatar asked Dec 20 '22 08:12

tgoneil


2 Answers

you're actually adding redundant "'" (which your echo invocation shows)

try this:

#!/bin/sh
for f in *
do
ls "$f"
done
like image 84
Stefano Crespi Avatar answered Dec 22 '22 20:12

Stefano Crespi


change the following line from

ls "'$f'"

into

ls "$f"
like image 31
Fredrik Pihl Avatar answered Dec 22 '22 22:12

Fredrik Pihl