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 > $BACKUPDIR
Can anyone help?
sort -n -r |head -1 | cut -f2 - date orders the directory and outputs the entire name of the most recently modified (even if containing some space as cut default delimiter tab)
By default, bash shows just your current directory, not the entire path. To determine the exact location of your current directory within the file system, go to a shell prompt and type the command pwd. This tells you that you are in the user sam's directory, which is in the /home directory.
Dollar sign $ (Variable) The dollar sign before the thing in parenthesis usually refers to a variable. This means that this command is either passing an argument to that variable from a bash script or is getting the value of that variable for something.
BACKUPDIR=$(ls -td /backups/*/ | head -1)
$(...)
evaluates the statement in a subshell and returns the output.
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 directorieshead -1
returns the first itemI didn't know about */
until I found Listing only directories using ls in bash: An examination.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With