-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.

1

1 Answer 1

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.

2
  • 1
    remove the $ in front of $directory. Btw., well done.
    – user2849202
    Commented Jul 14, 2021 at 1:17
  • Or ls -1dt */ | head -n1 Commented Jul 14, 2021 at 1:24

Not the answer you're looking for? Browse other questions tagged or ask your own question.