Bash
Contents
Introduction
I am a huge bash fan. I love it. The more I learn it the more I love it.
It is weird in the same sort of way that perl is weird. It makes certain things very easy. If you learn these things and use them, then you will understand why bash is great. If you don't, then you will be fighting bash pointlessly.
What is a shell?
A shell is a program that allows you to interactively execute other programs. With a shell, you interact with commands and options, rather than point-and-click. It's the difference between human language and cavemen grunting at each other. Heck, cavemen probably had a wider vocabulary because they could make facial expressions. With a mouse you can only point and click.
How to Use Bash
Bash commands take the form of:
command args
The commands may be actual bash commands--export
, cd
, for instance--or they may be real programs that live in your $PATH
.
The commands that are programs are invoked, passing along your exported environment variables (env) as well as the args. These are used to control the program's behavior.
Bash has a lot of extensions. For instance, you can take the output of a command and store it in a file. You can take a file and pass it in as the input of the program. Or you can run a second program if the first program fails. We'll cover those shortly.
Important Environment Variables
$PATH
By far, the single most important environment variable is $PATH
. This tells bash where to look for programs to run. If you want to run a program that isn't in your path, you have to specify where it lives. As a security feature, if the program lives in the same directory as you are currently in, you have to preceed the command with './'. This keeps you from confusing the program with one that lives on your path.
If you would like to know where a program along your path actually is, use the which
program.
Arithmetic
You can use arithmetic in BASH.
- Use an Arithmetic Expansion which is simply $((...)).
$ echo $((7 + 4)) 11
The stuff inside is an Arithmetic Expression.
These are really useful. For instance, if you are suffering under the limits of an ext filesystem and organizing files hierarchically by storing them in some form of:
/123/456/789/789456123
to prevent too many files showing up in a directory, you can use an expression like:
/$((ID%1000))/$((ID%1000000/1000))/$((ID%1000000000/1000000))/$ID
to find the directory where $ID lives.