Search code examples
bashunixdirectorycd

UNIX - How to write a bash script to automatically change to next/previous directory


Say I have this folder structure:

MainFolder
    Folder1
    Folder2
    Folder3
    ...
    Folder200

I want to write a script that, if I am current inside Folder2 and execute the script, it will automatically change to the next directory in the list, in this case, Folder3. The restrictions are that the folders could have any name, and I cannot rename it.

So my questions are:

1) How can I know what directory is next on the list? I was wondering if the subdirectories of a directory have a sequential index number that I could use to know what dir comes next.

2) Since I would like to display the name of the new directory at the end of the script, is there a way to display only the dir name? (eg: Folder3 instead of /home/path/to/dir/Folder3 which is the result of "pwd")


Solution

    1. What defines the order in which the directories are to be processed? If you have directories without spaces and other special characters in their names, you can use ls to list the directories in order, and then find the name after the current directory:

      cwd=$(basename $PWD)
      nwd=$(ls .. | awk "/^$cwd$/ { found = 1; next; } { if (found) { print; found = 0 } }")
      if [ -d ../$nwd ]
      then cd ../$nwd
      fi
      
    2. The name of the directory (only) is found using basename $PWD or ${PWD##*/}.