Get the newest directory in bash to a variables

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

    There is a simple solution to this using only ls:

    BACKUPDIR=$(ls -td /backups/*/ | head -1)
    
    • -t orders by time (latest first)
    • -d only lists items from this folder
    • */ only lists directories
    • head -1 returns the first item

    I didn't know about */ until I found Listing only directories using ls in bash: An examination.

提交回复
热议问题