Get the newest directory in bash to a variables

后端 未结 8 2079
北恋
北恋 2020-12-13 13:17

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 &         


        
8条回答
  •  爱一瞬间的悲伤
    2020-12-13 13:58

    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.

提交回复
热议问题