<?xml version="1.0"?>
<linuxdoc><article opts="null"><titlepag><title>BASH Programming - Introduction HOW-TO</title><author><name>by Mike G <tt>mikkey at dynamo.com.ar</tt></name></author><date> 	Thu Jul 27 09:36:18 ART 2000
    </date><abstract>     This article intends to help you to start programming     basic-intermediate shell scripts. It does not intend to be an     advanced document (see the title). I am NOT an expert nor guru     shell programmer. I decided to write this because I'll learn a     lot and it might be useful to other people. Any feedback will be apreciated,     specially in the patch form :)     </abstract></titlepag><toc></toc><sect><heading>Introduction</heading><sect1><heading>Getting the latest version</heading><p><htmlurl url="http://www.linuxdoc.org/HOWTO/Bash-Prog-Intro-HOWTO.html" name="http://www.linuxdoc.org/HOWTO/Bash-Prog-Intro-HOWTO.html"></htmlurl></p><p></p><p></p></sect1><sect1><heading>Requisites
          </heading><p> Familiarity with GNU/Linux command lines, and familiarity 
with basic programming concepts is helpful. While this is not
a programming introduction, it explains (or at least tries) many
basic concepts.</p><p> </p></sect1><sect1><heading>Uses of this document
          </heading><p> This document tries to be useful in the following situations
<itemize><item> You have an idea about programming and you want to start 
coding some shell scripts.</item><item> You have a vague idea about shell programming and want 
some sort of reference.</item><item> You want to see some shell scripts and some comments to
start writing your own</item><item> You are migrating from DOS/Windows (or already did) 
and want to make "batch" processes.</item><item> You are a complete nerd and read every how-to available</item></itemize></p></sect1></sect><sect><heading>Very simple Scripts
    </heading><p> This HOW-TO will try to give you some hints about shell script
programming strongly based on examples.</p><p> In this section you'll find some little scripts which 
will hopefully help you to understand some techniques.</p><p></p><sect1><heading>Traditional hello world script
        
	</heading><p><tscreen><verb>	  #!/bin/bash          
	  echo Hello World    
	</verb></tscreen></p><p> </p><p> This script has only two lines. 
The first indicates the system which program 
to use to run the file. </p><p> The second line is the only action performed by this script, 
which prints 'Hello World' on the terminal.</p><p> If you get something like <it>./hello.sh: Command not found.</it>
Probably the first line 'ent!/bin/bash' is wrong, issue whereis bash or see 
'finding bash' to see how sould you write this line. </p></sect1><sect1><heading>A very simple backup script
        </heading><p><tscreen><verb>	#!/bin/bash          
	tar -cZf /var/my-backup.tgz /home/me/
	</verb></tscreen></p><p> In this script, instead of printing a message on the terminal, 
we create a tar-ball of a user's home directory. This is NOT intended
to be used, a more useful backup script is presented later in this 
document.</p></sect1></sect><sect><heading>All about redirection
	</heading><sect1><heading>Theory and quick reference
	</heading><p> There are 3 file descriptors, stdin, stdout and stderr (std=standard).</p><p></p><p>Basically you can:
<enum><item> redirect stdout to a file</item><item> redirect stderr to a file</item><item> redirect stdout to a stderr </item><item> redirect stderr to a stdout </item><item> redirect stderr and stdout to a file </item><item> redirect stderr and stdout to stdout </item><item> redirect stderr and stdout to stderr</item></enum>
1 'represents' stdout and 2 stderr.</p><p> A little note for seeing this things: with the less command you can view both stdout 
(which will remain on the buffer) and the stderr that will be printed on the screen, but erased as 
you try to 'browse' the buffer. </p></sect1><sect1><heading>Sample: stdout 2 file 	</heading><p> This will cause the ouput of a program to be written to a file.
<tscreen><verb>	ls -l ent ls-l.txt
	</verb></tscreen>
Here, a file called 'ls-l.txt' will be created and it will contain what you would see on the 
screen if you type the command 'ls -l' and execute it.</p></sect1><sect1><heading>Sample: stderr 2 file 	</heading><p> This will cause the stderr ouput of a program to be written to a file.
<tscreen><verb>	grep da * 2ent grep-errors.txt
	</verb></tscreen>
Here, a file called 'grep-errors.txt' will be created and it will contain what you would see
the stderr portion of the output of the 'grep da *' command.</p></sect1><sect1><heading>Sample: stdout 2 stderr
	</heading><p> This will cause the stderr ouput of a program to be written to the same filedescriptor 
than stdout.
<tscreen><verb>	grep da * 1entent2 
	</verb></tscreen>
Here, the stdout portion of the command is sent to stderr, you may notice that in differen ways.</p></sect1><sect1><heading>Sample: stderr 2 stdout 	</heading><p> This will cause the stderr ouput of a program to be written to the same filedescriptor 
than stdout.
<tscreen><verb>	grep * 2entent1
	</verb></tscreen>
Here, the stderr portion of the command is sent to stdout, if you pipe to less, you'll see that
lines that normally 'dissapear' (as they are written to stderr) are being kept now (because
they're on stdout). </p></sect1><sect1><heading>Sample: stderr and stdout 2 file 	</heading><p> This will place every output of a program to a file. This is suitable sometimes 
for cron entries, if you want a command to pass in absolute silence.  
<tscreen><verb>	rm -f $(find / -name core) entent /dev/null 
	</verb></tscreen>
This (thinking on the cron entry) will delete every file called 'core' in any directory. Notice
that you should be pretty sure of what a command is doing if you are going to wipe it's output. </p></sect1></sect><sect><heading>Pipes
	</heading><p> This section explains in a very simple and practical way how to use pipes, 
nd why you may want it.</p><p></p><sect1><heading>What they are and why you'll want to use them
		</heading><p> Pipes let you use (very simple, I insist) the output of a program as the 
input of another one	</p></sect1><sect1><heading>Sample: simple pipe with sed 	</heading><p> This is very simple way to use pipes.
<tscreen><verb>	ls -l | sed -e "s/[aeio]/u/g"	
	</verb></tscreen>
Here, the following happens: first the command ls -l is executed, and it's output, 
instead of being printed, is sent (piped) to the sed program, which in turn, prints
what it has to. </p></sect1><sect1><heading>Sample: an alternative to ls -l *.txt 	</heading><p> Probably, this is a more difficult way to do ls -l *.txt, but it is here for illustrating pipes,
not for solving such listing dilema. 
<tscreen><verb>	ls -l | grep "\.txt$"
	</verb></tscreen>
Here, the output of the program ls -l is sent to the grep program, which, in turn, will print 
lines which match the regex "\.txt$".</p></sect1></sect><sect><heading>Variables
    
        </heading><p> You can use variables as in any programming languages. 
There are no data types. A variable in bash can contain a number, a
character, a string of characters. </p><p>  You have no need to declare a variable, just 
assigning a value to its reference will create it.</p><p></p><p></p><p></p><sect1><heading>Sample: Hello World! using variables
            </heading><p> 
<tscreen><verb>	    #!/bin/bash          
	    STR="Hello World!"
	    echo $STR    
	    </verb></tscreen></p><p></p><p> Line 2 creates 
a variable called STR and assigns the string "Hello World!" to
it. Then the VALUE of this variable is retrieved by putting 
the '$' in at the beginning. Please notice (try it!) 
that if you don't use the '$' sign, the output of the program will
be different, and probably not what you want it to be.</p></sect1><sect1><heading>Sample: A very simple backup script (little bit better)
	   </heading><p> 
<tscreen><verb>	   #!/bin/bash          
	   OF=/var/my-backup-$(date +%Y%m%d).tgz
	   tar -cZf $OF /home/me/
	   </verb></tscreen></p><p> This script introduces another thing. First 
of all, you should be familiarized with the variable 
creation and assignation on line 2. Notice the expression
'$(date +entYentmentd)'.
If you run the script you'll notice that 
it runs the
command inside the parenthesis, capturing its output. </p><p></p><p> Notice that in this script, the output filename will
be different every day, due to the format switch to the date command(+entYentmentd).
You can change this by specifying a different format.</p><p> Some more examples:</p><p> echo ls</p><p> echo $(ls)</p></sect1><sect1><heading>Local variables
	</heading><p> Local variables can be created by using the keyword <it>local</it>.</p><p><tscreen><verb>		#!/bin/bash
		HELLO=Hello 
		function hello {
			local HELLO=World
			echo $HELLO
		}
		echo $HELLO
		hello
		echo $HELLO
	</verb></tscreen></p><p> This example should be enought to show how to use a local variable. </p></sect1></sect><sect><heading>Conditionals
    </heading><p> Conditionals let you decide whether to perform an action 
or not, this decision is taken by evaluating an expression.</p><p></p><sect1><heading>Dry Theory
        </heading><p> Conditionals have many forms. The most basic form is:
<bf>if</bf> <it>expression</it> <bf>then</bf> <it>statement</it>
where 'statement' is only executed if 'expression' 	
evaluates to true.
'2ent1' is an expresion that evaluates to false, while '2ent1' 
evaluates to true.xs</p><p> Conditionals have other forms such as:
<bf>if</bf> <it>expression</it> 
<bf>then</bf> <it>statement1</it> <bf>else</bf> <it>statement2</it>.
Here 'statement1' is executed  if 'expression' is true,otherwise
'statement2' is executed.</p><p> Yet another form of conditionals is:  
<bf>if</bf> <it>expression1</it> 
<bf>then</bf> <it>statement1</it> 
<bf>else if</bf> <it>expression2</it> <bf>then</bf> <it>statement2</it> 
<bf>else</bf> <it>statement3</it>.
In this form there's added only the
"ELSE IF 'expression2' THEN 'statement2'" which makes statement2 being
executed if expression2 evaluates to true. The rest is as you may 
imagine (see previous forms).</p><p> A word about syntax:</p><p> The base for the 'if' constructions in bash is this:</p><p> if entexpression];</p><p> then</p><p>    code if 'expression' is true.</p><p> fi</p></sect1><sect1><heading>Sample: Basic conditional example if .. then
            </heading><p> 
<tscreen><verb>	    #!/bin/bash
	    if [ "foo" = "foo" ]; then
	       echo expression evaluated as true
	    fi
	    </verb></tscreen></p><p> The code to be executed if the expression within braces 
is true can 
be found after the 'then' word and before 'fi' which indicates the end 
of the conditionally executed code.</p></sect1><sect1><heading>Sample: Basic conditional example if .. then ... else
	    </heading><p><tscreen><verb>	    #!/bin/bash
	    if [ "foo" = "foo" ]; then
	       echo expression evaluated as true
	    else
	       echo expression evaluated as false
	    fi
	    </verb></tscreen></p></sect1><sect1><heading>Sample: Conditionals with variables
	    </heading><p> 
<tscreen><verb>	    #!/bin/bash
	    T1="foo"
	    T2="bar"
	    if [ "$T1" = "$T2" ]; then
	        echo expression evaluated as true
	    else
	        echo expression evaluated as false
	    fi
	    </verb></tscreen></p></sect1></sect><sect><heading>Loops for, while and until
    
    </heading><p> In this section you'll find for, while and until loops.</p><p> The <bf>for</bf> loop is a little bit different from other programming
languages. Basically, it let's you iterate over a series of 
'words' within a string.</p><p> The <bf>while</bf> executes a piece of code if the control expression
is true, and only stops when it is false (or a explicit break is found
within the executed code.</p><p> The <bf>until</bf> loop is almost equal to the while loop, except that
the code is executed while the control expression evaluates to false.</p><p> If you suspect that while and until are very similar you are right.
    </p><sect1><heading>For sample
        </heading><p> 
<tscreen><verb>        #!/bin/bash
        for i in $( ls ); do
            echo item: $i
        done
        </verb></tscreen></p><p> </p><p> On the second line, we declare i to be the variable that
will take the 
different values contained in $( ls ).</p><p> The third line could be longer if needed, or there could
be more lines 
before the done (4).</p><p> 'done' (4) indicates that the code that used the value of $i has
finished and $i can take a new value.</p><p> This script has very little sense, but a more useful way to use the
for loop would be to use it to match only certain files on the previous
example</p><p></p></sect1><sect1><heading>C-like for
	</heading><p> fiesh suggested adding this form of looping. It's a for loop
more similar to C/perl... for.
<tscreen><verb>	#!/bin/bash
	for i in `seq 1 10`;
	do
		echo $i
	done	
	</verb></tscreen></p></sect1><sect1><heading>While sample
         </heading><p> <tscreen><verb>         #!/bin/bash 
         COUNTER=0
         while [  $COUNTER -lt 10 ]; do
             echo The counter is $COUNTER
             let COUNTER=COUNTER+1 
         done
         </verb></tscreen></p><p></p><p> This script 'emulates' the well known 
(C, Pascal, perl, etc) 'for' structure</p></sect1><sect1><heading>Until sample
         </heading><p> <tscreen><verb>         #!/bin/bash 
         COUNTER=20
         until [  $COUNTER -lt 10 ]; do
             echo COUNTER $COUNTER
             let COUNTER-=1
         done
	 </verb></tscreen></p></sect1></sect><sect><heading>Functions
     </heading><p> As in almost any programming language, you can use functions to group 
pieces of code in a more logical way or practice the divine art of recursion.</p><p> Declaring a function is just a matter of writing function myentfunc ent myentcode ent.</p><p> Calling a function is just like calling another program, you just write its name.</p><p></p><sect1><heading>Functions sample
           </heading><p> <tscreen><verb>	   #!/bin/bash 
	   function quit {
	       exit
	   }
	   function hello {
	       echo Hello!
	   }
	   hello
	   quit
	   echo foo 
	   </verb></tscreen></p><p> Lines 2-4 contain the 'quit' function. Lines 5-7 contain the 'hello' function
If you are not absolutely sure about what this script does, please try it!.</p><p> Notice that a functions don't need to be declared in any specific order.</p><p> When running the script you'll notice that first: the function 'hello' is 
called, second the 'quit' function, and the program never reaches line 10.</p></sect1><sect1><heading>Functions with parameters sample
           </heading><p> <tscreen><verb>		#!/bin/bash 
		function quit {
 		   exit
		}  
		function e {
		    echo $1 
		}  
		e Hello
		e World
		quit
		echo foo 

	   </verb></tscreen></p><p> This script is almost identically to the previous one. The main difference is the 
funcion 'e'. This function, prints the first argument it receives. 
Arguments, within funtions, are treated in the same manner as arguments given to the script.</p></sect1></sect><sect><heading>User interfaces
     
     </heading><sect1><heading>Using select to make simple menus
	   </heading><p><tscreen><verb>	   #!/bin/bash
	   OPTIONS="Hello Quit"
	   select opt in $OPTIONS; do
	       if [ "$opt" = "Quit" ]; then
	   	echo done
	   	exit
	       elif [ "$opt" = "Hello" ]; then
	   	echo Hello World
	       else
	   	clear
	   	echo bad option
	       fi
	   done
	  </verb></tscreen> </p><p> If you run this script you'll see that it is a 
programmer's dream for text based menus. You'll probably notice 
that it's very similar to the 'for' construction, only rather 
than looping for each 'word' in $OPTIONS, it prompts the user.</p><p></p></sect1><sect1><heading>Using the command line          </heading><p><tscreen><verb>	  #!/bin/bash        
          if [ -z "$1" ]; then 
              echo usage: $0 directory
              exit
          fi
          SRCD=$1
          TGTD="/var/backups/"
          OF=home-$(date +%Y%m%d).tgz
          tar -cZf $TGTD$OF $SRCD
	 </verb></tscreen></p><p></p><p> What this script does should be clear to you. The expression 
in the first conditional tests if the program has received an argument
($1) and quits if it didn't, showing the user a little usage message.
The rest of the script should be clear at this point.</p></sect1></sect><sect><heading>Misc
         </heading><sect1><heading>Reading user input with read
         </heading><p> In many ocations you may want to prompt the user for some input, and 
there are several ways 
to achive this. This is one of those ways:
<tscreen><verb>		#!/bin/bash
		echo Please, enter your name
		read NAME
		echo "Hi $NAME!"
	</verb></tscreen></p><p> As a variant, you can get multiple values with read, this example may 
clarify this.
<tscreen><verb>		#!/bin/bash
		echo Please, enter your firstname and lastname
		read FN LN 
		echo "Hi! $LN, $FN !"
	</verb></tscreen></p><p></p></sect1><sect1><heading>Arithmetic evaluation
         </heading><p> On the command line (or a shell) try this:</p><p> echo 1 + 1</p><p> If you expected to see '2' you'll be disappointed. What if 
you want BASH to evaluate some numbers you have? The solution
is this:</p><p> echo $((1+1))</p><p> This will produce a more 'logical' output. This is to evaluate an
arithmetic expression. You can achieve this also like this:</p><p> echo $ent1+1]</p><p></p><p> If you need to use fractions, or more math or you just want it, you 
can use bc to evaluate arithmetic expressions.</p><p> if i ran "echo $ent3/4]" at the command prompt, it would return 0 
because bash  only uses integers when answering. If you  ran
"echo 3/4entbc -l", it would properly return 0.75.</p></sect1><sect1><heading>Finding bash         </heading><p> From a message from mike (see Thanks to) </p><p> you always use ent!/bin/bash .. you might was to give an example of</p><p> how to find where bash is located.</p><p> 'locate bash' is preferred, but not all machines have locate.</p><p> 'find ./ -name bash' from the root dir will work, usually.</p><p> Suggested locations to check:</p><p>         ls -l /bin/bash</p><p>         ls -l /sbin/bash</p><p>         ls -l /usr/local/bin/bash</p><p>         ls -l /usr/bin/bash</p><p>         ls -l /usr/sbin/bash</p><p>         ls -l /usr/local/sbin/bash</p><p> (can't think of any other dirs offhand...  i've found it in</p><p> most of these places before on different system).</p><p> You may try also 'which bash'.</p></sect1><sect1><heading>Getting the return value of a program
        </heading><p> In bash, the return value of a program is stored in a special variable called $?.</p><p> This illustrates how to capture the return value of a program, I assume that the directory
<it>dada</it> does not exist. (This was also suggested by mike)
<tscreen><verb>	#!/bin/bash
	cd /dada entent /dev/null
	echo rv: $?
	cd $(pwd) entent /dev/null
	echo rv: $?
	</verb> </tscreen></p></sect1><sect1><heading>Capturing a commands output          </heading><p> This little scripts show all tables from all databases (assuming you got MySQL installed). 
Also, consider changing the 'mysql' command to use a valid username and password.
<tscreen><verb>	#!/bin/bash
	DBS=`mysql -uroot  -e"show databases"`
	for b in $DBS ;
	do
	        mysql -uroot -e"show tables from $b"
	done
	</verb></tscreen></p></sect1><sect1><heading>Multiple source files
        </heading><p> You can use multiple files with the command source. </p><p> ententTO-DOentent</p></sect1></sect><sect><heading>Tables
    
    </heading><sect1><heading>String comparison operators
    </heading><p> (1) s1 = s2</p><p> (2) s1 != s2</p><p> (3) s1 ent s2</p><p> (4) s1 ent s2</p><p> (5) -n s1 </p><p> (6) -z s1 </p><p> </p><p> (1) s1 matches s2</p><p> (2) s1 does not match s2</p><p> (3) ententTO-DOentent</p><p> (4) ententTO-DOentent</p><p> (5) s1 is not null (contains one or more characters)</p><p> (6) s1 is null </p></sect1><sect1><heading>String comparison examples
	</heading><p> Comparing two strings. 
<tscreen><verb>	#!/bin/bash
	S1='string'
	S2='String'
	if [ $S1=$S2 ];
	then
	        echo "S1('$S1') is not equal to S2('$S2')"
	fi
	if [ $S1=$S1 ];
	then
	        echo "S1('$S1') is equal to S1('$S1')"
	fi
	</verb></tscreen></p><p> I quote here a note from a mail, sent buy Andreas Beck, refering to use
<it>if ent $1 = $2 ]</it>.</p><p>  This is not quite a good idea, as if either $S1 or $S2 is empty, you will
get a parse error. x$1=x$2 or "$1"="$2" is better.</p><p></p></sect1><sect1><heading>Arithmetic operators
    </heading><p> +</p><p> -</p><p> *</p><p> /</p><p> ent (remainder)</p></sect1><sect1><heading>Arithmetic relational operators
    </heading><p> -lt (ent) </p><p> -gt (ent)</p><p> -le (ent=)</p><p> -ge (ent=)</p><p> -eq (==)</p><p> -ne (!=)</p><p> C programmer's should simple map the operator to its corresponding 
parenthesis.</p></sect1><sect1><heading>Useful commands
         </heading><p> This section was re-written by Kees (see thank to...) </p><p>  Some of these command's almost contain complete programming languages. 
From those commands only the basics will be explained. For a more detailed 
description, have a closer look at the man pages of each command.</p><p><bf>sed</bf> (stream editor)</p><p></p><p> Sed is a non-interactive editor. Instead of altering a file by moving the 
cursor on the screen, you use a script of editing instructions to sed, plus the 
name of the file to edit. You can also describe sed as a filter. Let's have 
a look at some examples:</p><p><tscreen><verb>	$sed 's/to_be_replaced/replaced/g' /tmp/dummy
	</verb></tscreen></p><p></p><p> Sed replaces the string 'toentbeentreplaced' with the string 'replaced' and 
reads from the /tmp/dummy file. The result will be sent to stdout (normally 
the console) but you can also add 'ent capture' to the end of the line above so 
that sed sends the output to the file 'capture'.</p><p><tscreen><verb>   	$sed 12, 18d /tmp/dummy
	</verb></tscreen>	</p><p></p><p> Sed shows all lines except lines 12 to 18. The original file is not altered by this command.</p><p><bf>awk</bf> (manipulation of datafiles, text retrieval and processing)</p><p></p><p> Many implementations of the AWK programming language exist (most known interpreters are GNU's
gawk and 'new awk' mawk.) The principle is simple: AWK scans for a pattern, and for every
matching pattern a action will be performed.</p><p> Again, I've created a dummy file containing the following lines:</p><p> <it>"test123</it></p><p> <it>test</it></p><p> <it>tteesstt"</it></p><p><tscreen><verb>	$awk '/test/ {print}' /tmp/dummy
	</verb></tscreen></p><p> test123</p><p></p><p> test</p><p></p><p> The pattern AWK looks for is 'test' and the action it performs when it found a line in the file
/tmp/dummy with the string 'test' is 'print'.</p><p><tscreen><verb>	$awk '/test/ {i=i+1} END {print i}' /tmp/dummy
	</verb></tscreen></p><p></p><p> 3</p><p></p><p> When you're searching for many patterns, you should replace the text between the quotes with '-f
file.awk' so you can put all patterns and actions in 'file.awk'.</p><p><bf>grep</bf> (print lines matching a search pattern)</p><p></p><p> We've already seen quite a few grep commands in the previous chapters, that display the lines
matching a pattern. But grep can do more.
<tscreen><verb>   	$grep "look for this" /var/log/messages -c
	</verb></tscreen></p><p> 12</p><p> The string "look for this" has been found 12 times in the file /var/log/messages.</p><p></p><p> entok, this example was a fake, the /var/log/messages was tweaked :-)]</p><p><bf>wc</bf> (counts lines, words and bytes)</p><p></p><p> In the following example, we see that the output is not what we expected. The dummy file, as used
in this example, contains the following text:
<it>"bash introduction</it>
<it> howto test file"</it></p><p><tscreen><verb>	$wc --words --lines --bytes /tmp/dummy
	</verb></tscreen></p><p></p><p> 2 5 34 /tmp/dummy</p><p></p><p> Wc doesn't care about the parameter order. Wc always prints them in a standard order, which is,
as you can see: <lines><words><bytes><filename>.</filename></bytes></words></lines></p><p><bf>sort</bf> (sort lines of text files)</p><p></p><p> This time the dummy file contains the following text:</p><p> <it>"b</it></p><p> <it>c</it></p><p> <it>a"</it>
<tscreen><verb>	$sort /tmp/dummy
	</verb></tscreen></p><p></p><p> This is what the output looks like:</p><p></p><p> <it>a</it></p><p> <it>b</it></p><p> <it>c</it></p><p></p><p> Commands shouldn't be that easy :-)
<bf>bc</bf> (a calculator programming language)</p><p></p><p> Bc is accepting calculations from command line (input from file. not from redirector or pipe),
but also from a user interface. The following demonstration shows some of the commands. Note that</p><p> I start bc using the -q parameter to avoid a welcome message.</p><p><tscreen><verb>   $bc -q
	</verb></tscreen></p><p></p><p> <it>1 == 5</it></p><p> <it>0</it></p><p> <it>0.05 == 0.05</it></p><p> <it>1</it></p><p> <it>5 != 5</it></p><p> <it>0</it></p><p> <it>2 ent 8</it></p><p> <it>256</it></p><p> <it>sqrt(9)</it></p><p> <it>3</it></p><p> <it>while (i != 9) ent</it></p><p> <it>i = i + 1;</it></p><p> <it>print i</it></p><p> <it>ent</it>	</p><p> <it>123456789</it></p><p> <it>quit</it></p><p><bf>tput</bf> (initialize a terminal or query terminfo database)</p><p></p><p> A little demonstration of tput's capabilities:
<tscreen><verb>	$tput cup 10 4
	</verb></tscreen></p><p> The prompt appears at (y10,x4).
<tscreen><verb>	$tput reset
	</verb></tscreen></p><p> Clears screen and prompt appears at (y1,x1). Note that (y0,x0) is the upper left corner.
<tscreen><verb>	$tput cols
	</verb></tscreen>
<it>80</it></p><p> Shows the number of characters possible in x direction.</p><p> It it higly recommended to be familiarized with these programs (at least). There are tons of
little programs that will let you do real magic on the command line.</p><p> entsome samples are taken from man pages or FAQs]</p></sect1></sect><sect><heading>More Scripts
     </heading><sect1><heading>Applying a command to all files in a directory.      </heading><p> </p></sect1><sect1><heading>Sample: A very simple backup script (little bit better)
	   </heading><p><tscreen><verb>	    #!/bin/bash          
	    SRCD="/home/"
	    TGTD="/var/backups/"
	    OF=home-$(date +%Y%m%d).tgz
	    tar -cZf $TGTD$OF $SRCD
	   </verb></tscreen> </p><p></p></sect1><sect1><heading>File re-namer
          </heading><p><tscreen><verb>          
             #!/bin/sh
             # renna: rename multiple files according to several rules
             # written by felix hudson Jan - 2000
             
             #first check for the various 'modes' that this program has
             #if the first ($1) condition matches then we execute that portion of the
             #program and then exit
             
             # check for the prefix condition
             if [ $1 = p ]; then
             
             #we now get rid of the mode ($1) variable and prefix ($2)
               prefix=$2 ; shift ; shift
             
             # a quick check to see if any files were given
             # if none then its better not to do anything than rename some non-existent
             # files!!
             
               if [$1 = ]; then
                  echo "no files given"
                  exit 0
               fi
             
             # this for loop iterates through all of the files that we gave the program
             # it does one rename per file given
               for file in $*
                 do
                 mv ${file} $prefix$file
               done
             
             #we now exit the program
               exit 0
             fi
             
             # check for a suffix rename
             # the rest of this part is virtually identical to the previous section
             # please see those notes
             if [ $1 = s ]; then
               suffix=$2 ; shift ; shift
             
                if [$1 = ]; then
                 echo "no files given"
                exit 0
                fi
             
              for file in $*
               do
                mv ${file} $file$suffix
              done
             
              exit 0
             fi
             
             # check for the replacement rename
             if [ $1 = r ]; then
             
               shift
             
             # i included this bit as to not damage any files if the user does not specify
             # anything to be done
             # just a safety measure
             
               if [ $# -lt 3 ] ; then
                 echo "usage: renna r [expression] [replacement] files... "
                 exit 0
               fi
             
             # remove other information
               OLD=$1 ; NEW=$2 ; shift ; shift
             
             # this for loop iterates through all of the files that we give the program
             # it does one rename per file given using the program 'sed'
             # this is a sinple command line program that parses standard input and
             # replaces a set expression with a give string
             # here we pass it the file name ( as standard input) and replace the nessesary
             # text
             
               for file in $*
               do
                 new=`echo ${file} | sed s/${OLD}/${NEW}/g`
                 mv ${file} $new
               done
             exit 0
             fi
             
             # if we have reached here then nothing proper was passed to the program
             # so we tell the user how to use it
             echo "usage;"
             echo " renna p [prefix] files.."
             echo " renna s [suffix] files.."
             echo " renna r [expression] [replacement] files.."
             exit 0
             
             # done!
             
	  </verb></tscreen></p></sect1><sect1><heading>File renamer (simple)
     </heading><p><tscreen><verb>     #!/bin/bash
     # renames.sh
     # basic file renamer

     criteria=$1
     re_match=$2
     replace=$3
     
     for i in $( ls *$criteria* ); 
     do
         src=$i
	 tgt=$(echo $i | sed -e "s/$re_match/$replace/")
	 mv $src $tgt
     done
     </verb></tscreen></p></sect1></sect><sect><heading>When something goes wrong (debugging)
     </heading><sect1><heading>Ways Calling BASH           </heading><p> A nice thing to do is to add on the first line
<tscreen><verb>	  #!/bin/bash -x
	  </verb></tscreen></p><p> This will produce some intresting output information</p></sect1></sect><sect><heading>About the document
     </heading><p> Feel free to make suggestions/corrections, or whatever you think 
it would be interesting to see in this document. I'll try to update
it as soon as I can.</p><sect1><heading>(no) warranty
          </heading><p> This documents comes with no warranty of any kind.
and all that </p></sect1><sect1><heading>Translations
     	</heading><p> Italian: by William Ghelfi (wizzy at tiscalinet.it) 
<htmlurl url="http://web.tiscalinet.it/penguin_rules" name="is here"></htmlurl></p><p> French: by Laurent Martelli 
<htmlurl url="http://" name="is missed"></htmlurl></p><p> Korean: Minseok Park 
<htmlurl url="http://kldp.org" name="http://kldp.org"></htmlurl></p><p> Korean: Chun Hye Jin 
<htmlurl url="" name="unknown"></htmlurl></p><p> Spanish: unknow 
<htmlurl url="http://www.insflug.org" name="http://www.insflug.org"></htmlurl></p><p> I guess there are more translations, but I don't have any info of them, 
if you have it, please, mail it to me so I update this section.</p></sect1><sect1><heading>Thanks to
     </heading><p><itemize><item> People who translated this document to other languages (previous section).</item><item> Nathan Hurst for sending a lot of corrections.</item><item> Jon Abbott for sending comments about evaluating arithmetic expressions.</item><item> Felix Hudson for writing the <it>renna</it> script</item><item> Kees van den Broek 
(for sending many corrections, re-writting usefull comands section)</item><item> Mike (pink) made some suggestions about locating bash and testing files</item><item> Fiesh make a nice suggestion for the loops section. </item><item> Lion suggested to mention a common error (./hello.sh: Command not found.)</item><item> Andreas Beck made several corrections and coments.</item></itemize></p></sect1><sect1><heading>History
	</heading><p> New translations included and minor correcitons.</p><p> Added the section usefull commands re-writen by Kess.</p><p> More corrections and suggestions incorporated.</p><p> Samples added on string comparison.</p><p> v0.8 droped the versioning, I guess the date is enought. </p><p> v0.7 More corrections and some old TO-DO sections written.</p><p> v0.6 Minor corrections.</p><p> v0.5 Added the redirection section.</p><p> v0.4 disapperd from its location due to my ex-boss and thid doc found it's new place 
at the proper url: www.linuxdoc.org.</p><p> prior:  I don't rememeber and I didn't use rcs nor cvs :(</p></sect1><sect1><heading>More resources
          </heading><p></p><p> Introduction to bash (under BE)
<htmlurl url="http://org.laol.net/lamug/beforever/bashtut.htm" name="http://org.laol.net/lamug/beforever/bashtut.htm"></htmlurl></p><p> Bourne Shell Programming 
http://207.213.123.70/book/ </p></sect1></sect></article></linuxdoc>

