This is really a job for zsh.
vim my_dir/*(om[1])
The bits in parentheses are glob qualifiers. The *
before is a regular glob pattern, for example if you wanted to consider only log files you could use *.log
. The o
glob qualifier changes the order in which the matches are sorted; om
means sort by modification time, most recent first. The [
glob qualifier means to only return some of the matches: [1]
returns the first match, [2,4]
return the next three, [-2,-1]
return the last two and so on. If the files have names that begin with their timestamp, *([1])
will suffice.
In other shells, there's no good way to pick the most recent file. If your file names don't contain unprintable characters or newlines, you can use
vim "$(ls -t mydir | head -n 1)"
If you want to pick the first or last file based on the name, there is a fully reliable and portable method, which is a bit verbose for the command line but perfectly serviceable in scripts.
set -- mydir/*
first_file_name=$1
eval "last_file_name=\${$#}"