Save Time on the UNIX/Linux Command Line by Specifying Multiple File Names
brian_s 270002K5X3 Comment (1) Visits (8102)
Many people are not aware that you can specify multiple file names on the command line for most commands that manipulate files.
For example, if there were serveral files I wanted to change permissions on I can list all the file names on a single "chmod" command line:
$ chmod 400 /tmp/file1 /home/file5 /etc/testfile
This is more efficient than specifying 3 seperate commands:
$ chmod 400 /tmp/file1
This same technique works for almost any command that deals with files such as: ls, chown, chgrp, chown, grep, cat, which, tail, etc.
Understanding the concept by understanding wildcards
Most UNIX/Linux admins know that you can do a command such as chmod 400 * with the * wildcard. When you do this, what the shell is actually doing is changing the * wildcard in to a list of the file names in the directory before it ever even runs the chmod command. When the shell runs chmod the shell provides it the list of files in the directory as an argument to chmod. So when you do "chmod 400 *" the chmod command doesn't know that you specified a * wildcard. All it is aware of is the list of file names that the shell has provided it as arguments. This can be illustrated by running this command:
$ echo ls -al *
You can see when I ran the command echo ls -al * the shell translated the * in to the list of file names. So when you run ls -al *, the command that is actually being run in the end is ls -al file1 file2 file3 file4 file5 file6
Moving and copying files
If you need to move or copy multiple files in to a directory you can easily do it in a single command. For example, if you wanted to back up several files in to the /tmp directory you can run a command such as cp /etc/passwd /etc/group /etc/resolv.conf /tmp This will copy these 3 files in to the /tmp directory.
When you stop and think about it this makes perfect sense. If you were to run a command such as mv * /tmp as we have already covered what the shell is doing is changing the * wildcard in to the list of file names in the dircetory before ever calling mv. Here is another example showing this by using the echo command to show what is really being run:
$ echo mv * /tmp
Killing processes and editing files with vi
The kill command supports specify multiple pids on a single command line, i.e: kill 3419 456 532
Even the vi command supports specify multiple files to edit on a single command line: vi file1 file2 file3 Once in vi you can run ":n" to move to the next file
But Don't go Overboard
One thing to keep in mind is that there is a limit to how long your command line can be. If you start running in to this limit you need to start looking at utilities such as xargs which can help.