Get the newest directory in bash to a variables

后端 未结 8 2072
北恋
北恋 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:57

    Well, I think this solution is the most efficient:

    path="/my/dir/structure/*"
    backupdir=$(find $path -type d -prune | tail -n 1)
    

    Explanation why this is a little better:

    We do not need sub-shells (aside from the one for getting the result into the bash variable). We do not need a useless -exec ls -d at the end of the find command, it already prints the directory listing. We can easily alter this, e.g. to exclude certain patterns. For example, if you want the second newest directory, because backup files are first written to a tmp dir in the same path:

    backupdir=$(find $path -type -d -prune -not -name "*temp_dir" | tail -n 1)
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题