Hello. Just started to study the bash and I just can’t think of a solution. It is necessary to write a shell script to which I can transfer a number of files, and it will give me the newest one in time. Ls -t command | head -1 will return me the newest file in the directory. How to write a script that could be executed from the console by transferring a list of files (for example, a list of 2,3,4..9 files) [The number of files is not known beforehand], and as a result of which, one of the most recent will be received file?

  • 3
    You can transfer the list of files with the parameters of the same ls - Mike
  • Thanks, I did not think of it myself right away)) It worked. And how can you do this with the find -cnewer command? - Graizer
  • -cnewer <FILE> - this is a little about that. - 0andriy

2 answers 2

A list of all the options and parameters passed to the script is available in the $@ variable. when referring to it, it makes sense to enclose it in quotes - "$@" , so that options / parameters that contain spaces ( 'пара метр1' пара\ метр2 , etc.) are not broken down into these same spaces.

  1. you can use the same ls program (the -t option sorts by the time of the last modification of the file, and in reverse order — the file modified most recently will be first on the list):

     #!/bin/bash ls -t "$@" | head -1 
  2. but you can go more difficult and long way. for example, use the stat program, which can output, for example, the file modification time ( %Y in the output format string specified by the -c option):

     #!/bin/bash stat -c '%Y %n' "$@" | sort | tail -1 | cut -d ' ' -f 2- 

    Finds the most recent file and displays only its name.

     ls -t | head -2 | tail -n1 | tr -s " " | cut -d" " -f 9