[英]Create shell alias with value from current path
I want to create a shell alias which would run 我想创建一个可以运行的shell别名
command ew --constantswitch --anotherconstantswitch <name>
Now the value name
needs to be extracted from the current path. 现在,需要从当前路径中提取值
name
。 the current path looks like this 当前路径看起来像这样
[username@path-to-shell-xxxxxxxx]/path/to/directory/with/name%
How can I create an alias such that when I run aliasX
it will 如何创建别名,以便当我运行
aliasX
时
name
from current path (which is last value of the prompt) name
(这是提示的最后一个值) An alias may not be competent for the job, but a function surely do. 别名可能不能胜任这项工作,但一定可以使用某个功能。 Try this code:
试试这个代码:
myfunc() {
command ew --constantswitch --anotherconstantswitch "${PWD##*/}"
}
The trick is ${PWD##*/}
. 诀窍是
${PWD##*/}
。 You know the automatic variable $PWD
is exactly what you get when you run pwd
, as well as Bash's builtin string substitution ${var##pattern}
that removes pattern
from the left of the variable with maximum match. 您知道自动变量
$PWD
就是运行pwd
时得到的,以及Bash的内置字符串替换${var##pattern}
,该变量从变量左侧以最大匹配度删除pattern
。 So ${PWD##*/}
removes everything except the name after the last slash, which as you described is what you're looking for. 因此
${PWD##*/}
会删除除最后一个斜杠后的名称以外的所有内容,正如您所描述的,这是您要查找的名称。
In practice, a function is more versatile than an alias. 实际上,功能比别名更通用。 If you still need to add extra arguments to the command, append
"$@"
to the end of the command inside the function, so any argument that you pass to the function will be forwarded to the command. 如果仍然需要在命令中添加其他参数,请在函数内部的命令末尾附加
"$@"
,这样,传递给函数的任何参数都将转发到命令。
Since you're not trying to do anything involving arguments, an alias is actually possible: 由于您不打算做任何涉及参数的事情,因此实际上可以使用别名:
alias aliasX='echo "${PWD##*/}"'
This will print the current directory name when you use aliasX
. 使用
aliasX
时,这将打印当前目录名称。 Or, using your example: 或者,使用您的示例:
alias aliasX='command ew --constantswitch --anotherconstantswitch "${PWD##*/}"'
Notice that the alias must be in single quotes or $PWD
will expand when you define it instead of when you use it. 请注意,别名必须用单引号引起来,否则
$PWD
在定义别名时(而不是在使用别名时)会扩展。
For anything slightly more complex, you should use a function instead of an alias, as shown in iBug's answer . 对于稍微复杂一点的内容,您应该使用函数而不是别名,如iBug的answer所示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.