I have a loop in my script, which iterates over an array – myArray and I need to do some copying of files/directories on each iteration. The array can be like this –
myArray=('ajax' 'style/prod_styles' `path/to/some_file.php` 'templates' 'uploadify')
Taking this array, for elements without a /, I need to copy the entire folders and their contents – e.g. ajax, templates, uploadify. But for those having slashes – like style/prod_styles (Note that there can be multiple slashes), I need to copy only the last element (e.g. for /path/to/some/folder I need to copy only folder and its contents) and in case the parent folders are not existing in the destination (e.g. path, to, some are the parent folders), I need to just create those folders and then copy the last element (folder).
Earlier I guessed it would be easy to do an explode (like PHP’s explode()) with / inside the loop and then recursively start from the parent (path directory as per the above example) check if its child directory exists, if not create it, till we are done with the parent of the file/directory to be copied, then do the final copy.
If, however there is something simpler possible in bash to do this, please let me know.
Thanks,
Sandeepan
Unless I misunderstood your question, you probably don’t need to use an explode-like facility to achieve what you want.
Example:
Update:
Updated sample code to maintains relative path within destination. So
styles/prod_styleswill be copied to$DESTINATION/styles/prod_stylesbut all other stuff withinstyles/are not copied.Note that some additional checks need to be added if one cannot be sure that:
DESTINATIONexistsmyArrayare valid directories (not files)Update 2:
Example code updated to handle regular files as well as directory.