Penguins Unbound
User:goeko > Shell Scripting

Shell Scripting

Page last modified 11:59, 28 Jun 2011 by goeko

    This page has some notes about shell scripting.

     

    If you need more info about shell scripting I would highly suggest O'Reilly Books .

    I have found these O'Reilly Books useful

    "Linux in a Nutshell" (http://www.oreilly.com/catalog/linuxnut5/)

    "Unix in a Nutshell" (http://www.oreilly.com/catalog/unixnut4/)

    "Bash Cookbook" (http://www.oreilly.com/catalog/9780596526788/)

     

    White Space
    When shell programming you often have commands that format output for the screen, often using spaces.  This can be problemic because it is not easy to remove the spaces from the values you want to use. For example look at the output from route -n

    Kernel IP routing table
    Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
    10.2.0.0        0.0.0.0         255.255.0.0     U     1      0        0 eth0
    169.254.0.0     0.0.0.0         255.255.0.0     U     1000   0        0 eth0
    0.0.0.0         10.2.0.1        0.0.0.0         UG    0      0        0 eth0
    

    you can see there are alot of spaces in that. So it can be difficult to

     

    worse yet, it can be variable, ie the amount of space can change each time you run the commands; For example the

    bdolango@bdolang-oldlaptop:~$ uptime
     12:50:58 up 1 day,  1:35,  4 users,  load average: 0.12, 0.16, 0.12
    

    output from uptime will vary it's location based on how many users on the system. Not this isn't a impossible task, but it makes using the output a much more difficult, and often not worth progamming around.

    Well I have a quick and easy fixx for this( I am certian I am not the first one to come up with this, but I found it SOOOO useful I thought I would write it down! [and I am certian I will forget it]). Throught the beatuy of shell programming you can just take your multi-spaced output and echo it, which will reduce your output to a single spaced output which is easily parsed with cut! For example if we take the output from uptime...

     

    or the route example

     

    pretty quick and efficient fixx for the problem.

     

    Variable Substitution/Pattern Matching

    Variable Substitution
    ${variable#pattern} if pattern matches the begining of the var's value delete the shortest part that matches
    ${variable##pattern} if pattern matches the begining of the var's value delete the longest part that matches
    ${variable%pattern} if pattern matches the end of the var's value delete the shortest part that matches
    ${variable%%pattern} if pattern matches the end of the var's value delete the longest part that matches

     

    Shell Signal/Traps

    Here is a good page with info about using the traps in shell scripts.

    http://linuxcommand.org/wss0160.php

     

    Powered by MindTouch Core