简体   繁体   中英

Delay wildcard expansion in bash

I am trying to write a wrapper on ls that will output the most recently modified file matching an optional pattern.

For example, lst *pdf should output the most recently modified file ending in pdf .

The following code works, but only if I enclose my argument in quotes. (I have to type lst "*pdf" ).

#!/bin/bash
param="$1"
ls -1tr $param | tail -1

If I don't use the quotes, I get just the first file matching the pattern in alphabetical order. The reason must be that that's the first item returned when *pdf is interpolated by the shell, so it passes the expansion of *pdf to my script, instead of "*pdf" .

So what should I do? I suspect that I have to rewrite the script using whichever primitive functions ls itself draws on.

I have prepared for you the following script:

$ cat ls2.sh 
#!/bin/bash
param="$@"
for f in "${param:=*}"
do
   stat -c '%Y %n' $f
done | sort -k1 -n | tail -1 | cut -d' ' -f2

on the current folder:

$ ls -1tr
ls2.sh
2.pdf
1.pdf
3.pdf
1.txt
2.txt
3.txt

output:

$ ./ls2.sh 
3.txt
$ ./ls2.sh *.pdf
3.pdf
$ ./ls2.sh 3.txt
3.txt
$ ./ls2.sh *
3.txt

Explanations:

I use stat -c '%Y %n' $f to display the modification time and the file name of the files, with param="$@" I get all the arguments passed to the script if empty I replace it by * to have the same behavior as ls command

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM