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?
2 answers
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.
you can use the same ls program (the
-toption 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 -1but you can go more difficult and long way. for example, use the stat program, which can output, for example, the file modification time (
%Yin the output format string specified by the-coption):#!/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
-cnewer <FILE>- this is a little about that. - 0andriy