You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bash中获取当前目录最新修改文件名的最短字符写法?

Simplify Opening the Most Recently Modified Log File

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 -t sorts files by modification time (newest first)
  • head -n1 grabs 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 f targets only files in the current directory (no subfolders)
  • %T@ outputs the modification time as a Unix timestamp (easy to sort numerically)
  • sort -n sorts by timestamp (oldest to newest)
  • tail -1 picks 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 files
  • om sorts them by modification time (newest first)
  • [1] picks the first (newest) entry

That's as minimal as it gets!

内容的提问来源于stack exchange,提问作者Nick Constantine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:24:29