1

I am trying to write a script that will loop through directories, and rename the file in the sub directory to match that of the directory name. I am running into an issue where if a directory has spaces in the name, then that name is split up and I can't do anything with it like I need to.

For example, the folder structure is:

TopLevel
->this is a test
-->test.txt

My script so far is:

#!/bin/sh
topLevel="/dir1/dir2/TopLevel"
for dir in $(ls $topLevel)
do
    echo $dir # for testing purposes to make sure i'm getting the right thing
    # Get name of directory - i know how to do this
    # Rename file to match the name of the directory, with the existing extension - i know how to do this
done

My expected output would be

/dir1/dir2/TopLevel/this is a test

However, the actual output is

this
is
a
test

Can someone point me in the right direction? It's been awhile since I've done shell scripting. I'm trying to take this script one piece at a time and I seem to be stuck on getting this iteration down.

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255

1 Answers1

2

This is one of the main reasons why you should never try to parse the output of ls. If you just use shell globs, you can do:

for dir in /dir1/dir2/TopLevel/*/
do
    echo "$dir" ## note the quotes, those are essential
done

Comments

  • Note how I use for dir in /dir1/dir2/TopLevel/*/ and not just for dir in /dir1/dir2/TopLevel/*. This is to only iterate over directories. If you want both directories and files, use for f in /dir1/dir2/TopLevel/*.

  • The quotes around $dir are essential, you should always quote variables, especially if they contain whitespace.

Further reading:

terdon
  • 242,166