Saturday, April 30, 2016

Bash Script Note : redirection, pipe, variable



The Note is a quite review of what has been learnt on website :

http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-3.html

The Note is driven by examples of short snippets. The brief command function is formatted as COMMAND:DESCRIPTION.

ECHO: the function is the same as printf


3. All about redirection

Stdout, Stderr to a file

This will cause the ouput of a program to be written to a file.
        ls -l > ls-l.txt

This will cause the stderr ouput of a program to be written to a file.
        grep da * 2> grep-errors.txt
4.Pipes 

Pipes let you use the output of a program as the input of another one.
This is very simple way to use pipes.
        ls -l | sed -e "s/[aeio]/u/g"   
        
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.
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.
        ls -l | grep "\.txt$"
        
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$".

5.Variables
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.
You have no need to declare a variable, just assigning a value to its reference will create it.

            STR="Hello World!"
            echo $STR    
            

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.


A very simple backup script
           #!/bin/bash          
           OF=/var/my-backup-$(date +%Y%m%d).tgz
           tar -cZf $OF /home/me/
           
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 +%Y%m%d)'. If you run the script you'll notice that it runs the command inside the parenthesis, capturing its output.

Notice that in this script, the output filename will be different every day, due to the format switch to the date command(+%Y%m%d). You can change this by specifying a different format.
Some more examples:
echo ls
echo $(ls)

Local variables can be created by using the keyword local.

                #!/bin/bash
                HELLO=Hello 
                function hello {
                        local HELLO=World
                        echo $HELLO
                }
                echo $HELLO
                hello
                echo $HELLO

No comments:

Post a Comment