Bash (Command Line): Loop through directories in specified location, replacing directories in current directory (with backup)

/ Published in: Bash
Save to your folder(s)

This command line aims at moving directories from a target location to the present working directory (pwd), backing the pwd directories up as it encounters them.

The script works by:

1. Iterating through the contents of the target directory (using the unix ls command)

2. Checking whether the current object is a directory

3. Moving the pwd directory to a backup location using the unix mv command

4. Moving the target location's directory to the present working directory

5. Printing out the modified directory's name using the unix echo command

Copy this code and paste it in your HTML
  1. for subdir in `ls targetDir`; do if [ -d "$subdir" ]; then mv "$subdir" "backup/$subdir"; mv "targetDir/$subdir" "$subdir"; echo "$subdir"; fi; done

Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.