2

Approach

I have a directory with named folders, randomly, with blank spaces and periods.

I created a small loop (in a script) with the intention of renaming these folders. On the basis that these are my directories (test and empty):

$ ls -la
./
../
35._JK_io/
'43A. io kl_ -'/
'Mi.Nombre.es Adios'/

Note: We have tried (creo) that all the possibilities of listing and have worked at the time of differentiating between directories and folders.

Now, I proceeded to create a loop so that I would list only the directories and (in the future) rename them:

for archives in `sh -c 'ls -q */' sh`

do

echo  "$archives"
done

Issue

The problem is that when I run the script I get:

35._JK_io/:
43A.
io
kl_
-/:
Mi.Nombre.es
Adios/:

Question

How do I prevent this from happening to me and to appear with spaces and as only three files?

Observation

When executing other scripts on the folders it has obtained that 35._JK_io / is a directory but the other two are not

Thank you!!

1 Answers1

6

When looping over directories, especially when these have funky names, don't loop over the output of ls. In general, passing pathnames between programs needs to be done with great caution as Unix filenames may contain any characters apart from / and the nul character (\0).

Instead

for dirname in ./*/; do
    printf 'Directory name is "%s"\n' "$dirname"
done

The final / in the pattern ./*/ makes the pattern expand to directories only. The dirname variable will get values like ./some directory name/ when doing this. I included ./ at the start of the pattern, but you may remove this if you like. Just be aware that if you have directories that have a dash (-) as the first character in their names, then you would later have to use e.g. mv -- "$dirname" "$newname" (with the --) to stop mv from interpreting the dash in the name as a command line option. With ./ at the start of $dirname, the -- is not needed.

It is extra important to quote variable expansions as the shell would otherwise do word splitting and filename globbing on the values.

Related:

Kusalananda
  • 333,661