Quantcast
Viewing all articles
Browse latest Browse all 8

Answer by Kaz for Is it a UUOC (useless use of cat) to redirect one file to another?

< from > to

doesn't work because there is no command there; no process. The shell opens/creates the files and arranges the redirections (meaning that the file descriptors referencing these files are planted as 0 and 1: standard input and standard output). But there is nothing there to do execute a loop to read from standard input and write to standard output.

zsh makes this work by substituting a user-configurable command in this "null command" case. The command is not visible in the command line, but it's still there. A process is created for it and it works the same way. NULLCMD is cat by default, so < from > to actually means cat < from > to in zsh, unless NULLCMD is set to something else; it is an "implicit cat" command.

A "useless use of cat" occurs when cat is used as an intermediary to read from a file and feed the data to another process, whose file descriptor could just be connected to the original file.

If cat is removable from the situation, such that the remaining commands can still perform the same task, it is useless. If it is not removable, then it isn't useless.

# useless, removable:
$ cat archive.tar | tar tf -    #  -->  tar tf archive.tar

# not removable (in POSIX shell):
$ cat > file
abc
[Ctrl-D]

# likewise:
STRING=$(cat file)

A cat that is replacable isn't the same thing. For instance instead of cat > file we can use vi file to create the file. That's doesn't count as removal of cat, while using whatever is left to achieve the same task.

If cat is the only command in the pipeline, then of course it can't be removed; no rearrangement of whatever is left will do the equivalent job.

Some shell scripters use cat because they think it lets them move the input operand closer to the left side of the command line. However, redirections can be anywhere in the command line:

# If you're so inclined:
# move source archive operand to the left without cat:
$ < archive.tar tar xf - > listing

Viewing all articles
Browse latest Browse all 8

Trending Articles