Bash中获取当前目录最新修改文件名的最短字符写法?
Hey there, I feel your pain—copy-pasting filenames every time is such a drag. Let's get this workflow streamlined with minimal typing!
Quick Command to Get the Latest File
First, here are two ways to grab the most recently modified file in your current directory:
1. Super Concise (for "safe" filenames without spaces/special chars)
If your log filenames don't have spaces, quotes, or weird characters, this is the shortest possible command:
ls -t | head -n1
ls -tsorts files by modification time (newest first)head -n1grabs just the top (newest) entry
2. Safe for All Filenames (handles spaces/special chars)
If you deal with filenames that have spaces or special characters, use this more robust version—it avoids breaking on tricky names:
find . -maxdepth 1 -type f -printf "%T@ %p\n" | sort -n | tail -1 | cut -d' ' -f2-
find . -maxdepth 1 -type ftargets only files in the current directory (no subfolders)%T@outputs the modification time as a Unix timestamp (easy to sort numerically)sort -nsorts by timestamp (oldest to newest)tail -1picks the newest entry (last in the sorted list)cut -d' ' -f2-strips off the timestamp and leaves just the filename
Set Up Aliases for One-Click Access
To avoid typing those commands every time, add an alias to your shell config (.bashrc, .zshrc, etc.):
Basic Alias (use the concise or safe command above)
Add this line to your config file:
alias lastfile='ls -t | head -n1' # Or swap in the safe find command here
Then reload your config (e.g., source ~/.bashrc) and you can run:
less $(lastfile)
Even Better: Direct Alias to Open the Latest File
Skip the middleman entirely with an alias that opens the latest file directly in less:
alias lesslast='less $(find . -maxdepth 1 -type f -printf "%T@ %p\n" | sort -n | tail -1 | cut -d" " -f2-)'
Now just type lesslast and you're in!
Bonus: Zsh Users Get an Even Shorter Trick
If you use zsh, its globbing powers let you do this in one super-short line without any aliases:
less *(om[1])
*matches all filesomsorts them by modification time (newest first)[1]picks the first (newest) entry
That's as minimal as it gets!
内容的提问来源于stack exchange,提问作者Nick Constantine

