< Previous | Contents | Next >
Indentation And line-continuation
When employing long commands, readability can be enhanced by spreading the com- mand over several lines. In Chapter 17, we looked at a particularly long example of the find command:
More Formatting Tricks
[me@linuxbox ~]$ find playground \( -type f -not -perm 0600 -exec chmod 0600 ‘{}’ ‘;’ \) -or \( -type d -not -perm 0700 -exec chmod 0700 ‘{}’ ‘;’ \)
[me@linuxbox ~]$ find playground \( -type f -not -perm 0600 -exec chmod 0600 ‘{}’ ‘;’ \) -or \( -type d -not -perm 0700 -exec chmod 0700 ‘{}’ ‘;’ \)
Obviously, this command is a little hard to figure out at first glance. In a script, this com - mand might be easier to understand if written this way:
find playground \
\( \
-type f \
-not -perm 0600 \
-exec chmod 0600 ‘{}’ ‘;’ \
\) \
-or \
\( \
-type d \
-not -perm 0700 \
-exec chmod 0700 ‘{}’ ‘;’ \
\)
find playground \
\( \
-type f \
-not -perm 0600 \
-exec chmod 0600 ‘{}’ ‘;’ \
\) \
-or \
\( \
-type d \
-not -perm 0700 \
-exec chmod 0700 ‘{}’ ‘;’ \
\)
By using line-continuations (backslash-linefeed sequences) and indentation, the logic of this complex command is more clearly described to the reader. This technique works on the command line, too, though it is seldom used, as it is very awkward to type and edit. One difference between a script and a command line is that the script may employ tab characters to achieve indentation, whereas the command line cannot, since tabs are used to activate completion.
Configuring vim For Script Writing
The vim text editor has many, many configuration settings. There are several common options that can facilitate script writing:
:syntax on
turns on syntax highlighting. With this setting, different elements of shell syntax will be displayed in different colors when viewing a script. This is helpful for identifying certain kinds of programming errors. It looks cool, too. Note that for this feature to work, you must have a complete version of vim installed, and the file you are editing must have a shebang indicating the file is a shell script. If you have difficulty with the command above, try :set syntax=sh instead.
:set hlsearch
turns on the option to highlight search results. Say we search for the word “echo.” With this option on, each instance of the word will be highlighted.
:set tabstop=4
sets the number of columns occupied by a tab character. The default is 8 columns. Setting the value to 4 (which is a common practice) allows long lines to fit more easily on the screen.
:set autoindent
turns on the “auto indent” feature. This causes vim to indent a new line the same amount as the line just typed. This speeds up typing on many kinds of program- ming constructs. To stop indentation, type Ctrl-d.
These changes can be made permanent by adding these commands (without the leading colon characters) to your ~/.vimrc file.