This is a very short and incomplete introduction to the Bourne-Again Shell.
On the commandline most programs follow the simple principle of creating and modifying plain text. To make this approach extremly productive the Bash offers some mechanisms.
The so-called pipe character (|
) acts like a plug to send the output of one program to the input of another.
This way way you can easily plug together toolchains,
e.g.
`ls | rev`
combines the list
and revert
command.
To direct the output of a program into a file, instead of
another program, you can use the >
character.
ls *.* > somefile.txt
A single >
writes a new file, while a double >>
appends
to a file (if it exists).
Variables are another feature. The value of a variable may be accessed after defining through putting a $
in front of your variable name:
HELLO="Hello World" echo $HELLO
With backticks you can capsule the output of a program, this means the result of the command inside the backticks will generate command line text.
For example: if ls *.* | head -1
= some.txt, then
cat `ls *.* | head -1`
is the same as
cat some.txt
This is especially useful to define variables.
FILE=`ls *.* | head -1`
Loops
Since the Bash is not only a user interface, but a fairly powerful programming language, it offers loops, one of the most basic and powerful principles of computer programming.
for
–loops can be executed on a space separated list of ‘words’.
The loop-definition may be saved in a file or entered
directly on the commandline: for LETTER in A B; do echo $LETTER ;done
A for
–loop may of course be combined with a command capsuled in backticks.
for FILE in `ls *.*`; do echo $FILE; done
A while
–loop runs while a certain precondition is true:
while [ 1 -lt 2 ] do echo "true" done
-lt
means less than.
Also available:
-eq
= equal
-le
= less equal
-gt
= greater than
-ge
= greater equal
This loop will basically run forever, since 1 will always be less than 2.
Combined with a variable and upcounting inside backticks,
COUNT=0 while [ $COUNT -le 10 ] do echo $COUNT COUNT=`expr $COUNT + 1` done
the loop will stop.
You find a good introduction at floss manuals.
For a complete introduction check the Advanced Bash Scripting Guide.
For inspiration read $(echo echo) echo $(echo): Command Line Poetics