Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the newest directory to a variable in Bash

Tags:

bash

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?

like image 513
Jonathan Avatar asked Feb 14 '12 11:02

Jonathan


People also ask

How do I get the latest directory in Linux?

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)

How do I get the current directory in bash?

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.

What does $() mean in bash?

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.


2 Answers

BACKUPDIR=$(ls -td /backups/*/ | head -1) 

$(...) evaluates the statement in a subshell and returns the output.

like image 141
Femaref Avatar answered Nov 04 '22 10:11

Femaref


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.

like image 41
Martin Avatar answered Nov 04 '22 10:11

Martin