Changing Directories
Always check the error status of chdir, to avoid running commands in the wrong directory. Alternatively, use fully qualified paths to obviate the need for chdir(2).
#!/bin/sh cd $nosuchdir || exit 1 rsync elsewhere:/foo .
Without || exit 1 to abort the script should cd fail, the subsequent rsync command could move files to the wrong location or fill up the wrong partition.
- Redirection.
Redirection can take place (almost) anywhere, not just at the end.
$ echo a b >c $ echo >c a b $ >c echo a b
Placing the filename at the beginning allows easier editing of the search term at the end of the command.
$ </var/log/messages grep foo $ </var/log/messages grep bar $ </var/log/messages grep user1
- Pipe to command arguments.
I use xargs(1) frequently to convert output from something (file, or another program) to arguments to another command. For instance, to commit only modified files in a cvs sandbox where there may be conflicted, new, or other troublesome files mixed in, use the following.
$ cvs up | perl -ne 'print if s/M //' | xargs cvs ci
Depending on the editor, one can use concept above to open certain files for editing, for example, files in a cvs sandbox that have conflicts.
$ cvs up | perl -ne 'print if s/C //' | xargs vi ex/vi: Vi's standard input and output must be a terminal $ cvs up | perl -ne 'print if s/C //' | xargs emacs emacs: standard input is not a tty $ cvs up | perl -ne 'print if s/C //' | xargs bbedit
- Stubborn Files
Dealing with files that have odd characters in their names can often be a chore on Unix, as one cannot type in the names in question. One could use a graphical file manager tool, but I find those cumbersome, ill suited to dealing with large numbers of files, and usually not installed on server systems.
To simply delete the bad filenames, there are a few options.
- Qualify the path.
Files that being with a hyphen (such as a file -rf) will trigger option processing, as the shell is very stupid. These can be avoided by either disabling option processing, or prefixing a directory name to the file path.
$ ls -rf $ rm -rf $ ls -rf $ rm * $ ls -rf $ rm -- -rf $ ls $ touch ./-rf $ ls -rf $ rm ./-rf $ ls $
The -- argument only works on systems whose getopt(3) library supports the syntax. On other systems, or for portability, the qualified path option must be used.
- Find inode and delete by that.
Each file on a Unix filesystem has a inode number associated with it; knowing the inode number of the bad file allows us to search for and delete it.
$ ls -i * 615383 foo $ find . -inum 615383 -exec rm {} \;