Bash – cd to a name-unknown directory in a known path

bashdirectoryshell-script

I am trying to automate the deployment of a webapp under development that is frequently updated. The webapp comes in the form of a zip file with unknown name, and this directory structure:

unknown_name.zip
  └── unknown_folder_name
     └──all_the_application_files

I need a bash script to:

  • remove all the contents of /var/www/ [done]
  • uncompress the unknown_name.zip archive, in a given tmp path [done]
  • cd inside that known tmp path [done]
  • cd inside the unknown_folder_name extracted from the unknown_name.zip
  • move all_the_application_files to /var/www [easy if we solve previous bullet]

Important: inside the tmp directory there will be only one directory, the one I want to go inside. My current bash script:

rm -r /var/www/*
unzip ./\*.zip \* -d /home/lese/tmp-deploy
cd /home/lese/tmp-deploy
# HERE I WOULD cd unknown_folder_name
mv * /var/www/

Best Answer

Solution

If you know for sure there's exactly one directory and nothing else (no other folder and no other file) in the current directory, you can enter that directory with

cd *

If you know that there is only one directory, but there might be non-directory and non-symlink-to-directory files in the current directory, you can use

cd */.

to select only the directory.

Explanation

A single * is expanded by the shell to a list of all file names (which includes subdirectories) in the current directory (excluding hidden files, especially the directories . and .. which are always there). If the only thing in the current directory is the subdirectory to enter, this will expand to

cd unknown_folder_name

and thus do what you want.

The trick with */. is that this expands to the "self directory" (named .) in any subdirectory, which is of course the subdirectory itself. Since file names can never contain a /, and by assumption there's only one directory, the only name it expands to will be unknown_folder_name/., which is of course the same directory as unknown_folder_name.

Related Question