[英]Create shell alias with value from current path
我想创建一个可以运行的shell别名
command ew --constantswitch --anotherconstantswitch <name>
现在,需要从当前路径中提取值name
。 当前路径看起来像这样
[username@path-to-shell-xxxxxxxx]/path/to/directory/with/name%
如何创建别名,以便当我运行aliasX
时
name
(这是提示的最后一个值) 别名可能不能胜任这项工作,但一定可以使用某个功能。 试试这个代码:
myfunc() {
command ew --constantswitch --anotherconstantswitch "${PWD##*/}"
}
诀窍是${PWD##*/}
。 您知道自动变量$PWD
就是运行pwd
时得到的,以及Bash的内置字符串替换${var##pattern}
,该变量从变量左侧以最大匹配度删除pattern
。 因此${PWD##*/}
会删除除最后一个斜杠后的名称以外的所有内容,正如您所描述的,这是您要查找的名称。
实际上,功能比别名更通用。 如果仍然需要在命令中添加其他参数,请在函数内部的命令末尾附加"$@"
,这样,传递给函数的任何参数都将转发到命令。
由于您不打算做任何涉及参数的事情,因此实际上可以使用别名:
alias aliasX='echo "${PWD##*/}"'
使用aliasX
时,这将打印当前目录名称。 或者,使用您的示例:
alias aliasX='command ew --constantswitch --anotherconstantswitch "${PWD##*/}"'
请注意,别名必须用单引号引起来,否则$PWD
在定义别名时(而不是在使用别名时)会扩展。
对于稍微复杂一点的内容,您应该使用函数而不是别名,如iBug的answer所示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.