Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How could I use alias in xargs

Tags:

shell

zsh

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?

like image 299
zhuguowei Avatar asked Sep 25 '22 15:09

zhuguowei


1 Answers

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.

  • place it in a directory listed in your $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.

like image 120
mklement0 Avatar answered Oct 11 '22 07:10

mklement0