Bash Shell Scripting - 10 Seconds Guide _ All About Linux

Embed Size (px)

Citation preview

  • 8/13/2019 Bash Shell Scripting - 10 Seconds Guide _ All About Linux

    1/7

    2009/10/09/ 1:19 PMBash Shell Scripting - 10 Seconds Guide | All about Linux

    Page 1 of 7http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html

    Book Reviews OS Reviews Ubuntu Popular Movies Contact Me

    October 23, 2005

    Bash Shell Scripting - 10 Seconds GuideThis Bash shell scriptingguide is not a detailed study but a quick reference to the BASH syntax. Solets begin...

    Common Environment Variables

    PATH- Sets the search path for any executable command. Similar to the PATH variable in MSDOS.

    HOME- Home directory of the user.

    MAIL- Contains the path to the location where mail addressed to the user is stored.

    IFS- Contains a string of characters which are used as word seperators in the command lin e. Thestring normally consists of the space, tab and the newline characters. To see them you will have to doan octal dump as follows:

    $ echo $IFS | od -bc

    PS1and PS2- Primary and secondary prompts in bash. PS1 is set to $by default and PS2is set to '>'. To see the secondary prompt, just run the command :

    $ ls |

    ... and press enter.

    USER- User login name.

    TERM- indicates the terminal type being used. This should be set correctly for editors like Vim to workcorrectly.

    SHELL- Determines the type of shell that the user sees on logging in.

    Note:To see what are the values held by the above environment variables, just do an echo of thename of the variable preceeded with a $. For example, if I do the following:

    $ echo $USERravi

    ... I get the value stored in the environment variable USER.

    Some Bash Shell Scripting Rules

    The first line in your script must be #!/bin/bash... that is a #(Hash) followed by a !(bang) followed by the path of the shell. This line lets theenvironment know the file is a shell script and the location of the shell.

    Before executing your script, you should make the script executable. You do it by using thefollowing command:

    $ chmod ugo+x your_shell_script.sh

    The name of your shell script must end with a .sh. This lets the user know that the file is ashell script. This is not compulsary but is the norm.

    Conditional Statements'If' StatementThe 'if' statement evaluates a condition which accompanies its command line.syntax:

    if condition_is_truethen execute commands

    else execute commandsfi

    'if' condition also permits multiway branching. That is you can evaluate more conditions if the previouscondition fails.

    if condition_is_truethen execute commandselif another_condition_is_truethen execute commandselse execute commandsfi

    Get Posts Via Email

    Enter Email ID Sign Up

    with Google Friend Connect

    Followers (68) More

    Already a member? Sign in

    Follow

    Translate

    Select Language

    Gadgets powered by Google

    Top Posts-

    PostRank

    9.0GIMP 2.7.0

    has beenreleased

    8.8Computer

    Memory - Howmuch is good

    enough ?8.0Damn Smal

    Linux - DSL7.7Who writes

    Linux and Who

    supports it7.6Linux

    eventuallygarners a 1%

    market share7.4Nokia N900

    - A mobilecommunicator

    that runs on

    Linux

    Search

    http://api.postrank.com/log?url=http%3A%2F%2Flinuxhelp.blogspot.com%2F2009%2F08%2Fnokia-n900-mobile-communicator-that.htmlhttp://api.postrank.com/log?url=http%3A%2F%2Flinuxhelp.blogspot.com%2F2009%2F08%2Fwho-writes-linux-and-who-supports-it.htmlhttp://api.postrank.com/log?url=http%3A%2F%2Flinuxhelp.blogspot.com%2F2009%2F08%2Fwho-writes-linux-and-who-supports-it.htmlhttp://api.postrank.com/log?url=http%3A%2F%2Flinuxhelp.blogspot.com%2F2009%2F07%2Fcomputer-memory-how-much-is-good-enough.htmlhttp://twitter.com/aboutlinuxhttp://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.htmlhttp://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.htmlhttp://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.htmlhttp://linuxhelp.blogspot.com/http://linuxhelp.blogspot.com/http://linuxhelp.blogspot.com/http://linuxhelp.blogspot.com/http://linuxhelp.blogspot.com/https://chitika.com/publishers.php?refid=brahmohttp://www.adbrite.com/mb/landing_both.php?spid=97175&afb=125x125-1http://www.google.com/webmasters/gadgets.htmlhttp://twitter.com/aboutlinuxhttp://feeds.feedburner.com/AllAboutLinuxhttp://api.postrank.com/log?url=http%3A%2F%2Flinuxhelp.blogspot.com%2F2009%2F08%2Fnokia-n900-mobile-communicator-that.htmlhttp://www.postrank.com/feed/2900dd39add908547f01bb7142df05e5http://api.postrank.com/log?url=http%3A%2F%2Flinuxhelp.blogspot.com%2F2009%2F05%2Flinux-eventually-garners-1-market-share.htmlhttp://www.postrank.com/feed/2900dd39add908547f01bb7142df05e5http://api.postrank.com/log?url=http%3A%2F%2Flinuxhelp.blogspot.com%2F2009%2F08%2Fwho-writes-linux-and-who-supports-it.htmlhttp://www.postrank.com/feed/2900dd39add908547f01bb7142df05e5http://api.postrank.com/log?url=http%3A%2F%2Flinuxhelp.blogspot.com%2F2009%2F09%2Fdamn-small-linux-dsl_29.htmlhttp://www.postrank.com/feed/2900dd39add908547f01bb7142df05e5http://api.postrank.com/log?url=http%3A%2F%2Flinuxhelp.blogspot.com%2F2009%2F07%2Fcomputer-memory-how-much-is-good-enough.htmlhttp://www.postrank.com/feed/2900dd39add908547f01bb7142df05e5http://api.postrank.com/log?url=http%3A%2F%2Flinuxhelp.blogspot.com%2F2009%2F08%2Fgimp-270-has-been-released.htmlhttp://www.postrank.com/feed/2900dd39add908547f01bb7142df05e5http://www.postrank.com/publishershttp://translate.google.com/translate_thttp://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html#http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.htmlhttp://linuxhelp.blogspot.com/2009/01/contact-me.htmlhttp://linuxhelp.blogspot.com/2008/04/best-selling-movies-of-all-times.htmlhttp://linuxhelp.blogspot.com/2008/09/ubuntu-articles.htmlhttp://linuxhelp.blogspot.com/2006/06/operating-system-reviews.htmlhttp://linuxhelp.blogspot.com/2006/06/book-reviews-linux-programming-web.html
  • 8/13/2019 Bash Shell Scripting - 10 Seconds Guide _ All About Linux

    2/7

    2009/10/09/ 1:19 PMBash Shell Scripting - 10 Seconds Guide | All about Linux

    Page 2 of 7http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html

    Example :

    if grep "linuxhelp" thisfile.htmlthen echo "Found the word in the file"else echo "Sorry no luck!"fi

    If's Companion - Testtestis an internal feature of the shell. 'test' evaluates the condition placed on its right, and returnseither a true or false exit status. For this purpose, 'test' uses certain operators to evaluate the condition.

    They are as follows:

    Relational Operators

    -eq - Equal to

    -lt - Less than

    -gt - Greater than

    -ge - Greater than or Equal to

    -le - Less than or Equal to

    File related tests

    -f file - True if file exists and is a regular file.

    -r file - True if file exists and is readable.

    -w file - True if file exists and is writable.

    -x file - True if file exists and is executable.

    -d file - True if file exists and is a directory.

    -s file - True if file exists and has a size greater than zero.

    String tests

    -n str - True if string str is not a null string.

    -z str - True if string str is a null string.

    str1 == str2 - True if both strings are equal.

    str - True if string str is assigned a value and is not null.

    str1 != str2 - True if both strings are unequal.

    -s file - True if file exists and has a size greater than zero.

    Test also permits the checking of more than one expression in the same line.

    -a - Performs the AND function

    -o - Performs the OR function

    A few Example snippets of using test

    test $d -eq 25 && echo $d

    ... which means, if the value in the variable d is equal to 25, printthe value. Otherwise don't printanything.

    test $s -lt 50 && do_something

    if [ $d -eq 25 ]thenecho $dfi

    In the above example, I have used square brackets instead of the keywordtest - which is another wayof doing the same thing.

    if [ $str1 == $str2 ]thendo somethingfi

    if [ -n "$str1" -a -n "$str2" ]thenecho 'Both $str1 and $str2 are not null'fi

    ... above, I have checked if both strings are not null then execute the echo command.

    Things to remember while using test

    1. If you are using square brackets [] instead of test, then care should be taken to insert a spaceafter the [ and before the ].

    2. test is confined to integer values only. Decimal values are simply truncated.

    http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html#http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html#
  • 8/13/2019 Bash Shell Scripting - 10 Seconds Guide _ All About Linux

    3/7

    2009/10/09/ 1:19 PMBash Shell Scripting - 10 Seconds Guide | All about Linux

    Page 3 of 7http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html

    3. Do not use wildcards for testingstring equality - they are expanded by the shell to match the filesin your directory rather than the string.

    Case StatementCase statement is the second conditional offered by the shell.Syntax:

    case expression inpattern1) execute commands ;;pattern2) execute commands ;;

    ...esac

    The keywords here are in, case and esac. The ';;' is used as option terminators. The construct alsouses ')' to delimit the pattern from the action.

    Example:

    ...echo "Enter your option : "read i;

    case $i in1) ls -l ;;

    2) ps -aux ;;3) date ;;4) who ;;5) exitesac

    Note:The last case option need not have ;; but you can provide them if you want.

    Here is another example:

    case `date |cut -d" " -f1` inMon) commands ;;Tue) commands ;;

    Wed) commands ;;...esac

    Case can also match more than one pattern with each option.You can also use shell wild-cards formatching patterns.

    ...echo "Do you wish to continue? (y/n)"read ans

    case $ans inY|y) ;;[Yy][Ee][Ss]) ;;

    N|n) exit ;;[Nn][Oo]) exit ;;*) echo "Invalid command"esac

    In the above case, if you enter YeS, YES,yEs and any of its combinations, it will be matched.

    This brings us to the end of conditional statements.

    Looping Statementswhile loop

    Syntax :

    while condition_is_truedoexecute commandsdone

    Example:

    while [ $num -gt 100 ]dosleep 5done

    while :doexecute some commandsdone

    The above code implements a infinite loop. You could also write 'while true' instead of 'while :' .Here I would like to introduce two keywords with respect to looping conditionals. They are break andcontinue.

    http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html#
  • 8/13/2019 Bash Shell Scripting - 10 Seconds Guide _ All About Linux

    4/7

    2009/10/09/ 1:19 PMBash Shell Scripting - 10 Seconds Guide | All about Linux

    Page 4 of 7http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html

    break - This keyword causes control to break out of the loop.continue - This keyword will suspend the execution of all statements following it and switches control tothe top of the loop for the next iteration.

    until loop

    Until complements while construct in the sense that the loop body here is executed repeatedly as longas the condition remains false.Syntax:

    until falsedo

    execute commandsdone

    Example:

    ...until [ -r myfile ]dosleep 5done

    The above code is executed repeatedly until the file myfile can be read.

    for loop

    Syntax :

    for variable in listdoexecute commandsdone

    Example:

    ...for x in 1 2 3 4 5doecho "The value of x is $x";

    done

    Here the list contains 5 numbers 1 to 5. Here is another example:

    for var in $PATH $MAIL $HOMEdoecho $vardone

    Suppose you have a directory full of java files and you want to compile those. You can write a scriptlike this:

    ...for file in *.javadojavac $filedone

    Note:You can use wildcard expressions in your scripts.

    Special Symbols Used In BASH Scripting

    $* - This denotes all the parameters passed to the script at the time of its execution. Whichincludes $1, $2 and so on.

    $0 - Name of the shell script being executed.

    $# - Number of arguments specified in the command line.$? - Exit status of the last command.

    The above symbols are known as positional parameters. Let me explain the positional parameters withthe aid of an example. Suppose I have a shell script called my_script.sh . Now I execute this script inthe command line as follows :

    $ ./my_script.sh linux is a robust OS

    ... as you can see above, I have passed 5 parameters to the script. In this scenario, the values of thepositional parameters are as follows:

  • 8/13/2019 Bash Shell Scripting - 10 Seconds Guide _ All About Linux

    5/7

    2009/10/09/ 1:19 PMBash Shell Scripting - 10 Seconds Guide | All about Linux

    Page 5 of 7http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html

    $* - will contain the values 'linux','is','a','robust','OS'.

    $0 - will contain the value my_script.sh - the name of the script being executed.

    $# - contains the value 5 - the total number of parameters.

    $$ - contains the process ID of the current shell. You can use this parameter while givingunique names to any temporary files that you create at the time of execution of the shell.

    $1 - contains the value 'linux'

    $2 - contains the value 'is'

    ... and so on.

    The Set And Shift Statementsset- Lets you associate values with these positional parameters .For example, try this:

    $ set `date`$ echo $1$ echo $*$ echo $#$ echo $2

    shift- transfers the contents of a positional parameter to its immediate lower numbered one. This goeson as many times it is called.

    Example :

    $ set `date`$ echo $1 $2 $3$ shift$ echo $1 $2 $3$ shift$ echo $1 $2 $3

    To see the process Id of the current shell, try this:

    $ echo $$2667

    Validate that it is the same value by executing the following command:

    $ ps -f |grep bash

    Make Your BASH Shell Script Interactiveread statement

    Make your shell script interactive. read will let the user enter values while the script is being executed.When a program encounters the read statement, the program pauses at that point. Input entered

    through the keyboardid read into the variables following read, and the program execution continues.Eg:

    #!/bin/shecho "Enter your name : "read nameecho "Hello $name , Have a nice day."

    Exit Status Of The Last CommandEvery command returns a value after execution. This value is called the exit status or return value ofthe command. A command is said to be true if it executes successfully, and false if it fails. This can bechecked in the script using the $? positional parameter.

    Resources For More Detailed Study Of The BASH CommandLinux Shell Scripting Tutorial @ Cyberciti.biz

    Introduction to BASH Programming@ Tldp.org

    I hope you enjoyed reading this Bash shell scripting 10 seconds guide.

    Related Posts

    Netcat, nc command

    Guide to adding a new partition or drive to an existing system

    Linux file system hierarchy - the fun easy way

    Tweak your host file to block ad generating web sites

    Managing disk space with LVM

    Posted by Ravi Labels: bash shell, system administration

    http://linuxhelp.blogspot.com/search/label/system%20administrationhttp://linuxhelp.blogspot.com/search/label/bash%20shellhttp://linuxhelp.blogspot.com/2006/05/managing-disk-space-with-lvm.htmlhttp://linuxhelp.blogspot.com/2007/08/tweak-your-host-file-to-block-ad.htmlhttp://linuxhelp.blogspot.com/2008/05/linux-file-system-hierarchy-fun-easy.htmlhttp://linuxhelp.blogspot.com/2008/05/guide-to-adding-new-partition-or-drive.htmlhttp://linuxhelp.blogspot.com/2009/09/netcat-nc-command.htmlhttp://www.tldp.org/HOWTO/Bash-Prog-Intro-HOWTO.htmlhttp://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html#http://bash.cyberciti.biz/guide/Main_Pagehttp://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html#
  • 8/13/2019 Bash Shell Scripting - 10 Seconds Guide _ All About Linux

    6/7

    2009/10/09/ 1:19 PMBash Shell Scripting - 10 Seconds Guide | All about Linux

    Page 6 of 7http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html

    Share on -18 retweet

    Showing 6 Of 6 Comments

    Sort by Oldest first Community Page Subscribe by email

    Paul Tarjan 2 weeks agoLooks good.

    One small correction, it is ! (bang) not ! (ban). Bang is the loud sound of a gun. And sometimes #! ispronounced "shabang" : http://tldp.org/LDP/abs/html/sha-bang.htmlLikeReportReplyMore !

    alex 2 weeks agotest $d -eq 25 ; echo $dtest $s -lt 50; do_something

    should be

    test $d -eq 25 && echo $d

    test $s -lt 50 && do_somethingLikeReportReplyMore !

    Ravi 2 weeks agoThanks Alex. I wonder how I missed it. Corrected.LikeReportReplyMore !

    joe 2 weeks agoI used to do bash scripting; now I just write in Ruby and pipe stuff back and forth to the command linewhen I want to run system commands. It might be a little more obfuscated, but damn is it easier, andmy code ends up a lot cleaner than when I wrote in bash.LikeReportReplyMore !

    RealDeuce 2 weeks agoPlease for the love of POSIX, change the == string equality test to a single =. This works just as welland it is portable to other sh implementations (dash, sh, etc) as well as the test command /bin/test and/bin/[LikeReport

    ReplyMore !

    Ravi 2 weeks agoIn my understanding, single = is used for assigning values to a variable. For comparing twovariables, you use double == . I didn't know you could use one for the other. I will check it out.LikeReportReplyMore !

    Add New CommentYou are commenting as a Guest. You may select one to log into:

    Logged in as

    Logout from DISQUSLogged in asusing Facebook Connect (Logout)

    http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html#http://disqus.com/logout/?ctkn=21bc467119200cb06806902fa8e2f5b0http://disqus.com/AnonymousUser/http://disqus.com/profile/login/?next=article:35941435http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html#http://disqus.com/http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html#http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html#http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html#http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html#http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html#comment-17350075http://linuxhelp.blogspot.com/http://disqus.com/ravik/http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html#http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html#http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html#http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html#http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html#comment-17344503http://disqus.com/guest/106a0e691cdf0fccf8755d2b456e4cd0/http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html#http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html#http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html#http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html#http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html#comment-17324510http://disqus.com/guest/d1f36907049406f16fd6f8e44b9dc37d/http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html#http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html#http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html#http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html#http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html#comment-17349852http://linuxhelp.blogspot.com/http://disqus.com/ravik/http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html#http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html#http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html#http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html#http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html#comment-17308861http://disqus.com/guest/fe372d170d69ec6d289e50ef1a5788c7/http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html#http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html#http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html#http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html#http://tldp.org/LDP/abs/html/sha-bang.htmlhttp://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html#comment-17298983http://disqus.com/guest/b3bb70a4bace7f9bd49f48b149ab95f9/http://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html#http://allaboutlinux.disqus.com/10_seconds_guide_to_bash_shell_scripting/http://allaboutlinux.disqus.com/10_seconds_guide_to_bash_shell_scripting/latest.rsshttp://www.addtoany.com/share_savehttp://linuxhelp.blogspot.com/2005/10/10-seconds-guide-to-bash-shell.html#http://twitter.com/home/?status=RT+%40tweetmeme+All+about+Linux%3A+10+Seconds+Guide+to+Bash+Shell+Scripting+http%3A%2F%2Fbit.ly%2F7K2ZJhttp://tweetmeme.com/story/139405930/
  • 8/13/2019 Bash Shell Scripting - 10 Seconds Guide _ All About Linux

    7/7

    2009/10/09/ 1:19 PMBash Shell Scripting - 10 Seconds Guide | All about Linux

    Page 7 of 7http://linuxhelp blogspot com/2005/10/10-seconds-guide-to-bash-shell html

    Type your comment here.

    blog comments powered by DisqusNewer Post Home Older Post

    Content Copyright 2004-2009All about Linux- A site on Linux, Open Source and Free software.

    http://linuxhelp.blogspot.com/http://www.sitemeter.com/stats.asp?site=sm9ravi2005http://linuxhelp.blogspot.com/2005/10/make-your-bash-scripts-user-friendly.htmlhttp://linuxhelp.blogspot.com/http://linuxhelp.blogspot.com/2005/10/openofficeorg-version-20-definite.htmlhttp://disqus.com/