How can I use aliased commands with xargs? How can I use aliased commands with xargs? linux linux

How can I use aliased commands with xargs?


Aliases are shell-specific - in this case, most likely bash-specific. To execute an alias, you need to execute bash, but aliases are only loaded for interactive shells (more precisely, .bashrc will only be read for an interactive shell).

bash -i runs an interactive shell (and sources .bashrc).bash -c cmd runs cmd.

Put them together:bash -ic cmd runs cmd in an interactive shell, where cmd can be a bash function/alias defined in your .bashrc.

find -name \*bar\* | xargs bash -ic gi foo

should do what you want.

Edit: I see you've tagged the question as "tcsh", so the bash-specific solution is not applicable. With tcsh, you dont need the -i, as it appears to read .tcshrc unless you give -f.

Try this:

find -name \*bar\* | xargs tcsh -c gi foo

It worked for my basic testing.


Turn "gi" into a script instead

eg, in /home/$USER/bin/gi:

#!/bin/shexec /bin/grep -i "$@"

don't forget to mark the file executable.


The suggestion here is to avoid xargs and use a "while read" loop instead of xargs:

find -name \*bar\* | while read file; do gi foo "$file"; done

See the accepted answer in the link above for refinements to deal with spaces or newlines in filenames.