When To Avoid Command Substitution

Some circumstances make command substitution difficult to use. Such circumstances could require a little extra care; others could require a completely different method for processing your argument list.

Filenames Containing Special Characters

Do not use command substitution to generate a list of filename arguments if the names contain special characters. Filenames containing spaces or other characters with special meanings turn into multiple or malformed arguments. Suppose you want to edit files containing a particular string, using the following command:

% vi `grep -l string *`

If one of the qualifying files produced by grep is named Some File, the file ends up in the vi command as two arguments (Some and File), rather than one. You could avoid this problem by quoting the filenames as follows:

% vi `grep -l string * | sed "s/.*/'&'/"`

However, the command shown above is very ugly and easy to mistype. Quoting the names could be tricky if the names contain quote characters. You would benefit from a habit of naming your files without using special characters.

Using xargs Instead of Command Substitution

A command could produce a list of hundreds or thousands of filenames. For example, if you were trying to locate all the files under your current directory that contain a given string, you might try the command shown below. However, if you have a lot of files, the backquoted command might produce so much output that the command substitution would fail:

% grep ...

Get Using csh & tcsh now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.