Get the newest directory in bash to a variables

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

    This ia a pure Bash solution:

    topdir=/backups
    BACKUPDIR=
    
    # Handle subdirectories beginning with '.', and empty $topdir
    shopt -s dotglob nullglob
    
    for file in "$topdir"/* ; do
        [[ -L $file || ! -d $file ]] && continue
        [[ -z $BACKUPDIR || $file -nt $BACKUPDIR ]] && BACKUPDIR=$file
    done
    
    printf 'BACKUPDIR=%q\n' "$BACKUPDIR"
    

    It skips symlinks, including symlinks to directories, which may or may not be the right thing to do. It skips other non-directories. It handles directories whose names contain any characters, including newlines and leading dots.

提交回复
热议问题