Prepend name of directory to children folders

Hi, I am a shell scripting newbie. I am in need of a shell script that will prepend the name of the parent directory to the child directory.

For example if the shell script called rename.sh is invoked with ">rename.sh /home/foobar/Simple" and the structure of the folder Simple is :

Simple
|_A
|_B
|_C

I need the script to rename A, B and C to "Simple-A", "Simple-B" and "Simple-C" as shown below:

Simple
|_Simple-A
|_Simple-B
|_Simple-C

Thanks in advance for any help rendered.

#!/bin/sh


DIR=${1}
PREF=hzsho
cd $DIR
for i in `ls`; 
do 
        mv $i ${PREF}${i};
done

Please don't perpetrate this construct. It's a Useless Use of Backticks and it's wrong if there are any subdirectories. The correct way to loop over all files in a directory is simply

for i in *

If it were my script, I would perhaps also prefer for it to work in the current directory.

PREF=$(basename "$(pwd)")

... and do away with the DIR stuff. Otherwise, to conform with the original spec, you should use PREF=$(basename "$DIR")

Hi era and mirusnet,

Thanks so much for your immediate assistance. This is exactly what I was looking for...:slight_smile:

I have a minor follow up. If I were in the folder when the command is executed from within the parent folder, for example:

>/bin/folderRename.sh .

then the file names get set with the period and the name of the parent folder is not applied.

if [${1} eq '.'] 
  then 
   DIR=$PWD
  else
   DIR=${1}
fi
PREF=$(basename "$DIR")
cd $DIR
for i in *; 
do 
        mv $i ${PREF}${i};
done

I get a complaint stating "[.: command not found". Looks like I cannot use the "." for comparison.

Please assist. Thanks again.

You need a space after the [, just like after any other command. (Yes, it's a command. It's confusing at first.) Also before the closing bracket.

Thanks that was it..