Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use aliased commands with xargs?

Tags:

linux

tcsh

xargs

I have the following alias in my .aliases:

alias gi grep -i 

and I want to look for foo case-insensitively in all the files that have the string bar in their name:

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

This is what I get:

xargs: gi: No such file or directory 

Is there any way to use aliases in xargs, or do I have to use the full version:

   find -name \*bar\* | xargs grep -i foo 

Note: This is a simple example. Besides gi I have some pretty complicated aliases that I can't expand manually so easily.

Edit: I used tcsh, so please specify if an answer is shell-specific.

like image 324
Nathan Fellman Avatar asked Jun 11 '09 05:06

Nathan Fellman


People also ask

How do I run multiple commands in xargs?

To run multiple commands with xargs , use the -I option. It works by defining a replace-str after the -I option and all occurrences of the replace-str are replaced with the argument passed to xargs.

How do you pass arguments to xargs?

The -c flag to sh only accepts one argument while xargs is splitting the arguments on whitespace - that's why the double quoting works (one level to make it a single word for the shell, one for xargs).

How do you check if a command is aliased?

A: You need to use type command. It rells whether command is an alias, function, buitin command or executable command file. So for each command, it indicate how it would be interpreted if used as a command name.


2 Answers

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.

like image 169
camh Avatar answered Sep 20 '22 04:09

camh


Turn "gi" into a script instead

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

#!/bin/sh exec /bin/grep -i "$@" 

don't forget to mark the file executable.

like image 24
Peter Ericson Avatar answered Sep 19 '22 04:09

Peter Ericson