Linux自定义别名如何获取参数?传递参数至kill命令别名方法
Hey there! Great question—bash aliases don’t actually support direct parameter passing like you’re attempting with $input. The issue is that aliases are just simple string replacements; they don’t handle positional arguments (like the firefox in your close firefox example) the way you need.
But don’t worry, the fix is easy: replace your alias with a bash function. Functions are designed to accept arguments, and they work perfectly for this use case.
Here’s How to Set It Up
Instead of your alias, add this function to your .bash_aliases file:
close() { # Kill all processes matching the input argument, excluding the grep process itself kill $(ps -A | grep "$1" | grep -v grep | awk '{print $1}') }
A Few Simplified Alternatives
If you want a cleaner, more robust version, you can skip the pipe chain entirely with built-in tools:
- Use
pgrepto directly get process IDs for the target app:close() { kill $(pgrep "$1") } - Even better, use
pkillwhich combinespgrepandkillinto one step:close() { pkill "$1" }
How to Activate It
After saving the function in .bash_aliases, either restart your terminal or run this command to apply changes right away:
source ~/.bash_aliases
Now you can run close firefox (or any other app name) and it’ll kill all matching processes.
Why Your Original Aliase Failed
When you defined your alias with $input, bash tried to expand $input at the moment you created the alias (not when you ran it). Since $input wasn’t set then, the alias ended up being kill $(ps -A | grep | awk "{print $1}")—which is why passing an argument did nothing. Functions, on the other hand, keep the $1 placeholder until you run the command, where it gets replaced with your actual input.
内容的提问来源于stack exchange,提问作者Chico

