-1

I work in a software development company and every day upon my machine boot I have to execute the same commands to start coding. I recently decided to create a bash script to do that for me. The problem is that the commands I need to type have a single difference from one another, and that is the folder I need to access.

I always have to access a directory where it will contain folders with different versions of the company code (let's call it "codes" for the sake of the discussion), and everyday another folder is added to the "codes" directory (they update the company code everyday) with name as timestamp e.g. 2021-07-05-17-52-51.

To be able to create my automation script I need to be able to get into the "codes" directory and get the most recent folder added to it, or get the latest timestamp. I am new to bash and I couldn't find answers on how to get the last added folder to a directory using bash or someway to use tab and get the last one.

Dharman
  • 30,962
  • 25
  • 85
  • 135
John Galt
  • 50
  • 1
  • 4
  • 3
    Did you try googling "how to get the last added folder to a directory using bash"? There's https://stackoverflow.com/questions/1015678/get-most-recent-file-in-a-directory-on-linux/23034261 and https://stackoverflow.com/questions/9275964/get-the-newest-directory-to-a-variable-in-bash – KamilCuk Jul 13 '21 at 23:33

1 Answers1

3

You can use something like this: directory=$(ls -At1 | head -n 1)

An explanation in parts:

ls -At1 lists sorted by time with one entry per line

head -n 1 returns the first entry

$(...) runs the command as a subshell, evaluates, and sets directory to the name of the item with the most recent modified datestamp. If you want to ignore hidden files and folders, you can lose the -A flag from ls.

Deuce
  • 49
  • 6