Bash – The Bourne Again SHell
A generic Bash / Linux commandline article. Some handy stuff mainly for reference.
Config
Have a look here for a bash config script.
Operations
Rename a batch of files:
Say we have a whole bunch of files which some nitwit has accidentally called {filename}.wav.mp3 and we want them to be just {filename}.mp3. Here’s how:
for file in *.wav.mp3; do mv $file `basename $file .wav.mp3`.mp3; done
Encode a bunch of waves into mp3:
find . -name '*.wav' -exec lame --mp3input {} {}.mp3 \;
The find command is very powerful. Have a look here for an extensive howto.
Errors
Error opening terminal: xterm.
Some (ancient?) programs require an ANSI-compatible environment, and apparently think XTERM is not ANSI enough, refusing to work. This can be fixed by setting the environment variable TERM to ansi:
martijn@galactix:/$ env TERM=ansi
That should do the trick. An alternative is to set this in your ~/.bashrc file using “export TERM=ansi”.
Note that the behaviour of this ansi_xterm is quite different (such as when editing files in vim) which can be quite a pain so it is better (in my opinion) to write a shellscript which first sets the env TERM=ansi and then starts the program requiring ansi like so:
#!/bin/bash env TERM=ansi /path/to/executable arg1 arg2 ...
This leaves your console in the xterm mode which you’ve come to like so much.
On Bash integer mathematics
Say you want to perform some calculations in bash with something other than integers, you can use bc to do this:
#!/bin/bash
NUPPI=$(echo 'scale=9; 10*(7/3)' | bc)
echo $NUPPI
This tells bc to use up to 9 decimals. For more info on bc (besides ‘man bc’ 😉 have a lot at this excellent post.
Generating random numbers:
You can read random numbers from /dev/random:
od -An -N2 -d /dev/urandom
This gives a wide range of random numbers. But what if you need random numbers from a specific distribution?
python -c "import random; randval=random.uniform(-5,5); print randval"
for a uniform distribution between -5 and 5, or for a normal distribution with mu 0 and standard deviation of 1:
python -c "import random; randval=random.normalvariate(0,1); print randval"
more info at http://docs.python.org/library/random.html