使用管道作为参数的别名命令

g_s*_*sue 2 bash alias

我想在我的~/.bash_profile遗嘱中创建一个别名:

  1. 取两个参数 $1 $2
  2. 将这些传递给 diff
  3. 管道输出到 less

我还没有在 Stack 上找到任何可以满足我需要的解决方案,但请向我指出您知道的任何解决方案!以下几行出现在 my 中~/.bash_profile

alias reload='. ~/.bash_profile'
alias aliases='emacs ~/.bash_profile; reload'
function dif () { diff "$1" "$2" | less; }
alias different='dif' 
Run Code Online (Sandbox Code Playgroud)

当我尝试:

gsuehr$ reload
-bash: /Users/gregorysuehr/.bash_profile: line 93: syntax error: unexpected end of file 
Run Code Online (Sandbox Code Playgroud)

我确定我不了解如何使用 bash 函数。reload aliases如果我注释掉函数声明,我已经确认 2 个别名:按预期工作。任何人都可以分享有关以下方面的知识:

  1. 为什么会出现EOF错误?
  2. 如何使用 bash 中的函数来完成我在这里尝试的操作?

Gil*_*il' 7

您不能使用别名在参数后添加内容,您需要一个函数。别名仅用于为命令提供备用名称 ( alias myalias=mycommand) 或提供初始参数 ( alias myalias='foo --option1 --option2')。

在 bash 中,您可以使用任何function myfunction { … }myfunction () { … }function myfunction () { … }来定义函数。该表单myfunction () …具有可移植到所有 sh shell 的优点。带有function关键字的表单即使myfunction是别名也具有工作的优势(\myfunction () …在这种情况下,您可以使用标准表单工作)。除了别名之外,这些语法在 bash 中完全等效。

跟在函数名或 the()后面的必须是一个格式良好的复杂命令。从你的回答来看(你问题中的代码没有产生错误信息,显然你没有发布你测试的版本),你的错误是你写的复杂命令不正确。大括号{}仅当它们是命令中的第一件事时才被识别为开始列表和结束列表语法,因此您需要在结束大括号之前使用换行符或分号。

此外,diff与其将两个参数传递给其他参数并忽略其他参数,不如将它们全部传递。这"$@"就是为了。

function dif () { diff "$1" "$2" | less; }
Run Code Online (Sandbox Code Playgroud)

此外,交互式 bash 会话的自定义应该进入.bashrc,而不是.bash_profile. .bash_profile仅由登录 shell 读取,当您打开 bash 的新实例(例如在终端中)时不会读取它。由于 bash 的设计缺陷,.bashrc即使它们是交互式的,也不会被登录 shell 读取,因此您应该将此行放在您的.bash_profile

if [[ $- == *i* ]]; then . ~/.bashrc; fi
Run Code Online (Sandbox Code Playgroud)

dif~/.bashrc.