Ubuntu uses zsh, now have an alias
alias | grep sayhi
sayhi='echo hi'
sayhi foo
hi foo
However, I can't use this alias
in xargs
or bash, see below
➜ ~ echo foo | xargs -i sayhi {}
xargs: sayhi: No such file or directory
➜ ~ echo foo | awk '{print "sayhi "$0}'
sayhi foo
➜ ~ echo foo | awk '{print "sayhi "$0}'|bash
bash: line 1: sayhi: command not found
It seems I can't use alias
indirectly in command line.
So how could I use alias
in this situation?
Leaving aside the fact that you're dealing with two different shells:
xargs
can only invoke external utilities (executables), so by definition it can't invoke an alias (directly).
Piping to bash
will run in a child process that is unaware of your current shell's aliases (and non-interactive Bash instances will neither read the usual profile / initialization files nor expand aliases by default).
While you could make it work with many contortions that significantly complicate invocation, your best bet is convert your alias to a script and have xargs
/ bash
invoke that.
To get the same single-word invocation experience as with an alias:
create script sayhi
(without a filename suffix); example content, taken from your follow-up question:
#!/bin/bash
echo hi $@
make it directly executable: chmod +x sayhi
- that way you don't have to involve a shell executable to invoke it.
$PATH
variable.You will then be able to invoke your script like any other executable in your path - by filename only - and the sample commands from your question should work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With