Skip to content
Advertisement

Bash script to copy the directory structure from source directory into target directory

I am very new to Bash scritping and to get some practice, I am attempting to write a script that takes in a source directory and a destination directory. The script will search the source directory and copy its structure of sub-directories into the target directory (any files will be ignored, just the directories themselves will be duplicated). The source directory can have any number of sub-directories at any depth. What would be the best way to achieve this? I have started by attempting to write a recursive function where, if a directory is found, the function is called recursively onto this directory. However, due to my lack of experience with scripting, I have been stumped.

Here is what I have so far:

JavaScript

I know that this is just a skeleton function, and a lot more work would need to be put into it, but I’m just looking for guidance as to whether this is the correct way to go about this before I go any further, and if so, what would be my next step? How do I pass a directory into my function?

EDIT: Here is my solution thanks to Ivan’s help below #! /bin/bash

JavaScript

There are two issues with this solution:

  1. As Rany Albeg Wein explained below, using ‘ls’ is not a good solution – and I have seen why when there is a space in a directory/*.png name.

  2. I am also attempting to copy any *.png file from the source to the target and convert it to a *.jpg image in the target. How can I do this? I am attempting to use ImageMagick’s convert image.png image.jpg command, but do not know how to do so when the image.png is being referred to as $file?

Advertisement

Answer

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement