So I have a bunch of folders in the format of: .../course/year/... and I often reorganize them so that the format then changes to this: .../year/course/.... I've been meaning to learn how to write shell scripts and I'm very new to automation and shell scripting but I want to make a script that does this for me when I input a path to the folder that I want renamed. So for example I would have a command like: sh reorganize.sh .../course/year/... and it would "swap" the course folder and the year folder. The year folder has some contents inside and after the swap everything that was in the year folder should now be in the course folder. There are also multiple year folders, so 2018, 2019, 2020 each have their own folder inside the course folder. I appreciate any help with how I can go about doing this.

PS- When I say I'm fairly new, what I mean is that I know the basic behind variables and pipes and basic commands but don't have much knowledge otherwise.

  • I think you just need to rename ../$course/$year/ to ../$course/$course and then to ../$year/$course. You can do it with two mv commands Jun 7, 2020 at 19:28
  • @danielleontiev It makes sense to assume that those are no literals but should be read as $course/$year... Jun 7, 2020 at 19:30
  • @HaukeLaging I agree. Edited the comment Jun 7, 2020 at 19:33
  • Oh, I forgot to add that there are multiple year folders so there are 2018, 2019, and 2020 folders inside the course folder. My bad, fixed the question.
    – Ace Ryder
    Jun 7, 2020 at 20:31

1 Answer 1

#! /bin/bash

shopt -s nullglob

for course in *; do
    pushd "$course" >/dev/null
    for year in *; do
        mkdir -p "${rootdir}/${year}"
        mv --no-target-directory "$year" "${rootdir}/${year}/${course}"
    popd >/dev/null
    rmdir "$course"

When jumping between directories I consider it less error-prone to work with absolute paths (rootdir="$PWD") and pushd/popd instead of cd. Though this rather simple case does not demand that.

The mv --no-target-directory shall prevent unexpected effects if the script runs several times (with the former run aborting). Again, one could argue that in this case (moving within a filesystem) the dangerous case cannot occur. mv behaves differently depending on whether the target directory / new path exists or not. This option prevents that.

  • Thanks for your answer. If time permits a few words of explanation on salient aspects of your solution (eg. shell option setting, pushd and popd lines) at the end would probably go a long way for those who might browse this without the benefit of prior knowledge... Nothing fancy needed. ;-)
    – Cbhihe
    Jun 8, 2020 at 13:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.