I would like to find the newest sub directory in a directory and save the result to variable in bash.
Something like this:
ls -t /backups | head -1 &
To get the newest folder using ls -t you may have to differentiate files from folders if your directory doesn't have only directories. Using a simple loop you will have a safe and fast result and also allowing to easily implement different filters in the future:
while read i ; do if [ -d "${i}" ] ; then newestFolder="${i}" ; break ; fi ; done < <(ls -t)
Elaborated block:
while read currentItemOnLoop # While reading each line of the file
do
if [ -d "${currentItemOnLoop}" ] # If the item is a folder
then
newestFolder="${currentItemOnLoop}" # Then save it into the "newestFolder" variable
break # and stop the loop
else
continue # Look for the next newest item
fi
done < <(ls -t) # Sending the result of "ls -t" as a "file" to the "while read" loop
Beware of the continue logic on my elaborated block:
else
continue # Look for the next newest item
You won't use it. I've put it there just for the sake of your visibility as in this case it wouldn't affect the results.