December 17, 2010 Archives

2010-12-17 19:18:28

Some lesser-known Bash tricks

Though alternatives like the zsh exist, the Bourne-again shell is still the de facto standard among all Unix shells. Maybe that's why some people refer to it as the Windows of the shells - although there are now better alternatives around, most users still stick with it. I am one of these users - that's why today's blog entry is about some useful, but little-known bash features. ;-)
Note that you'll need at least Bash v4.0 for some of them.
The Bash built-in shopt allows you to (de)activate various variables in order to control optional shell behavior. shopt called without an argument gives you an overview of all available options. To activate a feature, simply issue shopt -s OPTION - if you'd like to deactivate the feature again, a shopt -u OPTION suffices. If you wonder what's so tricky about this, just read on - basic knowledge of shopt is needed to benefit from the following.
Everybody knows about the extremely useful for-loop, which allows it to perform the same command for all (or a subset of all) files in a directory. Its syntax is pretty much straightforward:

for file in *; do echo "Touching $file"; touch "$file"; done
This will touch every file in the current directory and tell you about it (not really a real world example, but you might get the point). However sometimes you'd like to also work on the files in all subdirectories - two popular solutions for this include the find command or recursion. As a rule, most users forget/don't know about the Bash's globstar option. If set (shopt -s globstar), you may use the following construct to also touch the files found in all subdirectories.
for file in **/*; do echo "Touching $file"; touch "$file"; done
Just want to touch all mp3 files? Here you go:
for file in **/*.mp3; do echo "Touching $file"; touch "$file"; done

Considering the previous example, you may notice that globbing doesn't include hidden files - which in most cases makes sense. Nevertheless, you can alter this standard behavior, by enabling the dotglob option using shopt

While the above examples mostly cover batch processing, some options only influence the interactive shell usage. If cdspell is set, the bash will generously ignore spelling mistakes in the directory component of a cd command:
user@host /var/tmp $ mkdir example_
user@host /var/tmp $ cd example
-bash: cd: example: No such file or directory
user@host /var/tmp $ shopt -s cdspell
user@host /var/tmp $ cd example
example_
user@host /var/tmp/example_ $
autocd does a very similar job - if you issue a valid directory name without the prepended cd, you will automatically change to that directory.

These are just some of the available options - man bash knows and explains them all, so start reading.... ;-)

Posted by haui | Permanent Link | Categories: linux