Reputation: 8704
I want to create a shell alias which would run
command ew --constantswitch --anotherconstantswitch <name>
Now the value name
needs to be extracted from the current path. 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
name
from current path (which is last value of the prompt)Upvotes: 1
Views: 749
Reputation: 37227
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##*/}
. 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. So ${PWD##*/}
removes everything except the name after the last slash, which as you described is what you're looking for.
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.
Upvotes: 7
Reputation: 52112
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
. 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.
For anything slightly more complex, you should use a function instead of an alias, as shown in iBug's answer.
Upvotes: 2