This question already has an answer here:

I have an executable which creates either file1 or file2 along with other files. I am trying to write a shell script which should output the latest created file. If the executable creates file1, the output should be file1. Please note that I already have both file1 and file2 exists in the directory along with other files. The executable overwrites it. If there are no file1/file2 exist, below script works but this doesn't work if both file1 and file2 exists.

if [ -e "file1" ]; then

marked as duplicate by Christopher, HalosGhost, sam, countermode, n.st Oct 21 '16 at 21:35

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


The quick and easy way.

output="$(ls -td control.tk input.scs 2> /dev/null|head -1)"

However I would only use this if you can make sure that the files don't contain funny characters like newlines or spaces. If you can guarantee that the filenames do not contain funny characters then parsing ls is quite safe.

  • Thanks Zachary. My files names are "input.scs" & "control.tk". – kumar Oct 21 '16 at 18:15
  • @kumar Then the above should work fine for you. – Zachary Brady Oct 21 '16 at 18:16
  • Also my executable creates several other files which I am not interested. I want to output either input.scs or control.tk based on when it is created. – kumar Oct 21 '16 at 18:17
  • @kumar checkout the updated answer. – Zachary Brady Oct 21 '16 at 18:19

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