Search code examples
bashls

Print content of a folder with a variable path in BASH


In my bash script I need to check the content of a folder, but its path can be changed with tree different "endings"

initially my folder is:

/home/myuser/my_folder

Then a user can modify the name of my folder with tree possibile endings

/home/myuser/my_folder_aaaa
/home/myuser/my_folder_bbbb
/home/myuser/my_folder_cccc

So, a user can add "_aaaa" or "_bbbb" "_cccc"

These suffixes are known.

In my bash script, how can I check with "ls" the content of my folder also in case someone changes the name? N.B: I need to check only this folder, so if there is a folder called "/home/myuser/my_folder_ssss" must not match and content must not be displayed


Solution

  • Seems that you need something like this:

    ls -1 | egrep "^my_folder(|_aaaa|_bbbb|_cccc)$"
    

    This command prints the name of the specified folder if it exists.

    ls -1 prints all items names inside the directory one per line.

    egrep checks if the name of item matches to my_folder or my_folder_aaaa, my_folder_bbbb, my_folder_cccc.

    Then you can do whatever you want with this name. For example, you can check the contents with:

    ls -l `ls -1 | egrep "^my_folder(|_aaaa|_bbbb|_cccc)$"`