A Tiny zsh Trick: Modify Your Last Command

작성자

카테고리:

← 피드로
DEV Community · Kenneth Lum · 2026-06-13 개발(SW)
Cover image for A Tiny zsh Trick: Modify Your Last Command

Kenneth Lum

Sometimes I run a command and immediately realize I only need to change one small part of it.

For example, say I just converted a video with ffmpeg:

ffmpeg -i calligraphy01.mp4 -c:v libx264 -c:a aac calligraphy_good_01.mp4

Enter fullscreen mode Exit fullscreen mode

Then I want to run the same command for the next file:

ffmpeg -i calligraphy02.mp4 -c:v libx264 -c:a aac calligraphy_good_02.mp4

Enter fullscreen mode Exit fullscreen mode

Instead of pressing the up arrow and manually editing both places, in zsh I can type:

!!:gs/01/02/

Enter fullscreen mode Exit fullscreen mode

That means:

Take the previous command, replace every 01 with 02, and run it.

So this:

!!:gs/01/02/

Enter fullscreen mode Exit fullscreen mode

expands to:

ffmpeg -i calligraphy02.mp4 -c:v libx264 -c:a aac calligraphy_good_02.mp4

Enter fullscreen mode Exit fullscreen mode

What the syntax means

!!

Enter fullscreen mode Exit fullscreen mode

means “the previous command”.

:gs/01/02/

Enter fullscreen mode Exit fullscreen mode

means “globally substitute 01 with 02”.

So the full command:

!!:gs/01/02/

Enter fullscreen mode Exit fullscreen mode

means:

Use the last command, replace all 01 with 02, then execute it.

Preview before running

Sometimes I do not want to run it immediately. I want to see the expanded command first.

For that, add :p:

!!:gs/01/02/:p

Enter fullscreen mode Exit fullscreen mode

This prints the modified command without executing it:

ffmpeg -i calligraphy02.mp4 -c:v libx264 -c:a aac calligraphy_good_02.mp4

Enter fullscreen mode Exit fullscreen mode

Then, if the command looks correct, press the up arrow to bring that printed command back into the prompt, review it one more time, and press Enter to run it.

So the safer workflow is:

!!:gs/01/02/:p

Enter fullscreen mode Exit fullscreen mode

Check the output, then:

Up Arrow → review command → Enter

Enter fullscreen mode Exit fullscreen mode

This is useful when the command is long, destructive, or expensive to run.

Replace only the first match

If you only want to replace the first occurrence, you can use:

^01^02

Enter fullscreen mode Exit fullscreen mode

But for commands like this ffmpeg example, where the number appears in both the input and output filename, !!:gs/01/02/ is usually what you want.

Tiny shell tricks like this save only a few seconds each time, but they make repeated command-line work feel much smoother.

원문에서 계속 ↗

코멘트

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다