{"id":4698,"date":"2015-05-02T22:26:51","date_gmt":"2015-05-02T14:26:51","guid":{"rendered":"http:\/\/rmohan.com\/?p=4698"},"modified":"2015-05-04T13:39:14","modified_gmt":"2015-05-04T05:39:14","slug":"bash-reference","status":"publish","type":"post","link":"https:\/\/mohan.sg\/?p=4698","title":{"rendered":"bash reference"},"content":{"rendered":"<p>Shell program<\/p>\n<p>View System Date, Calender<\/p>\n<p>Calender<\/p>\n<p>[root@cluster1 ~]# cal<br \/>\n     April 2015<br \/>\nSu Mo Tu We Th Fr Sa<br \/>\n          1  2  3  4<br \/>\n 5  6  7  8  9 10 11<br \/>\n12 13 14 15 16 17 18<br \/>\n19 20 21 22 23 24 25<br \/>\n26 27 28 29 30<\/p>\n<p>[root@cluster1 ~]# cal 7 2015<br \/>\n      July 2015<br \/>\nSu Mo Tu We Th Fr Sa<br \/>\n          1  2  3  4<br \/>\n 5  6  7  8  9 10 11<br \/>\n12 13 14 15 16 17 18<br \/>\n19 20 21 22 23 24 25<br \/>\n26 27 28 29 30 31<\/p>\n<p>date <\/p>\n<p>Syntax to specify format<br \/>\ndate +FORMAT<\/p>\n<p>[root@cluster1 ~]# date<br \/>\nMon Apr 27 23:14:35 SGT 2015<br \/>\n[root@cluster1 ~]# date &#8216;+DATE:%m-%y%nTime:%H:%M:%S&#8217;<br \/>\nDATE:04-15<br \/>\nTime:23:15:14<br \/>\n[root@cluster1 ~]#<\/p>\n<p>[root@cluster1 ~]# date +%Y%m%d<br \/>\n20150427<br \/>\n[root@cluster1 ~]# date +%Y-%m-%d<br \/>\n2015-04-27<br \/>\n[root@cluster1 ~]# date &#8216;+%d\/%m\/%Y_%H:%M:%S<br \/>\n[root@cluster1 ~]# date &#8216;+%d\/%m\/%Y_%H:%M:%S&#8217;<br \/>\n27\/04\/2015_23:16:39<br \/>\n[root@cluster1 ~]# date &#8216;+%d\/%m\/%Y-%H:%M:%S&#8217;<br \/>\n27\/04\/2015-23:16:49<\/p>\n<p>[root@cluster1 ~]# date +&#8221;%x %r %Z&#8221;<br \/>\n04\/27\/2015 11:18:01 PM SGT<\/p>\n<p>[root@cluster1 ~]# right_now=$(date +&#8221;%x %r %Z&#8221;)<br \/>\ntime_stamp=&#8221;Updated on $right_now by $USER&#8221;<br \/>\n[root@cluster1 ~]# echo $time_stamp<br \/>\nUpdated on 04\/27\/2015 11:18:23 PM SGT by root<\/p>\n<p>Task: Display date in mm-dd-yy format<br \/>\nType the command as follows:<br \/>\n$ date +&#8221;%m-%d-%y&#8221;<br \/>\nOutput:<br \/>\n02-27-07<br \/>\nTurn on 4 digit year display:<br \/>\n$ date +&#8221;%m-%d-%Y&#8221;<br \/>\nJust display date as mm\/dd\/yy format:<br \/>\n$ date +&#8221;%D&#8221;<br \/>\nTask: Display time only<br \/>\nType the command as follows:<br \/>\n$ date +&#8221;%T&#8221;<br \/>\nOutput:<br \/>\n19:55:04<br \/>\nDisplay locale\u2019s 12-hour clock time<br \/>\n$ date +&#8221;%r&#8221;<br \/>\nOutput:<br \/>\n07:56:05 PM<br \/>\nDisplay time in HH:MM format:<br \/>\n$ date +&#8221;%H-%M&#8221;<br \/>\nHow do I save time\/date format to a variable?<br \/>\nSimply type command as follows at a shell prompt:<br \/>\n$ NOW=$(date +&#8221;%m-%d-%Y&#8221;)<br \/>\nTo display a variable use echo \/ printf command:<br \/>\n$ echo $NOW<br \/>\nSample shell script:<br \/>\n#!\/bin\/bash<br \/>\nNOW=$(date +&#8221;%m-%d-%Y&#8221;)<br \/>\nFILE=&#8221;backup.$NOW.tar.gz&#8221;<br \/>\n# rest of script Complete list of FORMAT control characters supported by date command<br \/>\nFORMAT controls the output.It can be the combination of any one of the following:<br \/>\n%%<br \/>\na literal %<br \/>\n%a<br \/>\nlocale&#8217;s abbreviated weekday name (e.g., Sun)<br \/>\n%A<br \/>\nlocale&#8217;s full weekday name (e.g., Sunday)<br \/>\n%b<br \/>\nlocale&#8217;s abbreviated month name (e.g., Jan)<br \/>\n%B<br \/>\nlocale&#8217;s full month name (e.g., January)<br \/>\n%c<br \/>\nlocale&#8217;s date and time (e.g., Thu Mar 3 23:05:25 2005)<br \/>\n%C<br \/>\ncentury; like %Y, except omit last two digits (e.g., 21)<br \/>\n%d<br \/>\nday of month (e.g, 01)<br \/>\n%D<br \/>\ndate; same as %m\/%d\/%y<br \/>\n%e<br \/>\nday of month, space padded; same as %_d<br \/>\n%F<br \/>\nfull date; same as %Y-%m-%d<br \/>\n%g<br \/>\nlast two digits of year of ISO week number (see %G)<br \/>\n%G<br \/>\nyear of ISO week number (see %V); normally useful only with %V<br \/>\n%h<br \/>\nsame as %b<br \/>\n%H<br \/>\nhour (00..23)<br \/>\n%I<br \/>\nhour (01..12)<br \/>\n%j<br \/>\nday of year (001..366)<br \/>\n%k<br \/>\nhour ( 0..23)<br \/>\n%l<br \/>\nhour ( 1..12)<br \/>\n%m<br \/>\nmonth (01..12)<br \/>\n%M<br \/>\nminute (00..59)<br \/>\n%n<br \/>\na newline<br \/>\n%N<br \/>\nnanoseconds (000000000..999999999)<br \/>\n%p<br \/>\nlocale&#8217;s equivalent of either AM or PM; blank if not known<br \/>\n%P<br \/>\nlike %p, but lower case<br \/>\n%r<br \/>\nlocale&#8217;s 12-hour clock time (e.g., 11:11:04 PM)<br \/>\n%R<br \/>\n24-hour hour and minute; same as %H:%M<br \/>\n%s<br \/>\nseconds since 1970-01-01 00:00:00 UTC<br \/>\n%S<br \/>\nsecond (00..60)<br \/>\n%t<br \/>\na tab<br \/>\n%T<br \/>\ntime; same as %H:%M:%S<br \/>\n%u<br \/>\nday of week (1..7); 1 is Monday<br \/>\n%U<br \/>\nweek number of year, with Sunday as first day of week (00..53)<br \/>\n%V<br \/>\nISO week number, with Monday as first day of week (01..53)<br \/>\n%w<br \/>\nday of week (0..6); 0 is Sunday<br \/>\n%W<br \/>\nweek number of year, with Monday as first day of week (00..53)<br \/>\n%x<br \/>\nlocale&#8217;s date representation (e.g., 12\/31\/99)<br \/>\n%X<br \/>\nlocale&#8217;s time representation (e.g., 23:13:48)<br \/>\n%y<br \/>\nlast two digits of year (00..99)<br \/>\n%Y<br \/>\nyear<br \/>\n%z<br \/>\n+hhmm numeric timezone (e.g., -0400)<br \/>\n%:z<br \/>\n+hh:mm numeric timezone (e.g., -04:00)<br \/>\n%::z<br \/>\n+hh:mm:ss numeric time zone (e.g., -04:00:00)<br \/>\n%:::z<br \/>\nnumeric time zone with : to necessary precision (e.g., -04, +05:30)<br \/>\n%Z<\/p>\n<p>Retrieve yesterday date using bash shell <\/p>\n<p>$ date &#8216;+%A, %Y-%m-%d&#8217;<br \/>\nSaturday, 2014-06-28<br \/>\n$ date -d &#8220;yesterday&#8221; &#8216;+%A, %Y-%m-%d&#8217;<br \/>\nFriday, 2014-06-27<\/p>\n<p>[root@cluster1 ~]# echo &#8220;Today is `date +%A` `date +%e`th of `date +%B` &#8221;<br \/>\nToday is Wednesday 29th of April<\/p>\n<p>A specific date minus one day, formatted as we wish:<br \/>\ndate -d &#8220;2014-10-01 -1 day&#8221; +%Y-%m-%d<br \/>\n2014-09-30<\/p>\n<p>==============================================================================================================================<\/p>\n<p>Create Files &#038; Directories<\/p>\n<p>a) touch<br \/>\nb) mkdir <\/p>\n<p>mkdir dir1<br \/>\nmkdir &#8211; create directory<br \/>\nmkdir command can take more arguments. For example we can take two directories with only one command:<\/p>\n<p>mkdir dir2 dir3<br \/>\nmkdir &#8211; create two directories<br \/>\nmkdir command can also create entire directory tree. By using -p option mkdir will also create parent directories if required:<\/p>\n<p>mkdir -p dir4\/dir4.1 <\/p>\n<p>mkdir -m 744 dir5 <\/p>\n<p>mkdir -p \/home\/mohan\/test1 \/home\/mohan\/test2 \/home\/mohan\/test3 <\/p>\n<p>c) PWD<\/p>\n<p>d) cat <\/p>\n<p>cat > test<br \/>\nthis test file <\/p>\n<p>cat < test\nthis test file \n\n\ncat test test1 > test2 <\/p>\n<p>cat test2<br \/>\nthis test file<br \/>\nthis test1 file<\/p>\n<p>e) touch <\/p>\n<p>g) mv<\/p>\n<p>h) rm<\/p>\n<p>i) rmdir<\/p>\n<p>=======================================================================================================================<br \/>\nCopies, Links to Files &#038; Directories<\/p>\n<p>copy <\/p>\n<p>cp [OPTION]&#8230; [-T] SOURCE DEST<br \/>\ncp [OPTION]&#8230; SOURCE&#8230; DIRECTORY<br \/>\ncp [OPTION]&#8230; -t DIRECTORY SOURCE&#8230; <\/p>\n<p>-i, &#8211;interactive<br \/>\n       prompt before overwrite<br \/>\n-p     same as &#8211;preserve=mode,ownership,timestamps<br \/>\n-R, -r, &#8211;recursive<br \/>\n       copy directories recursively<br \/>\n-v, &#8211;verbose explain what is being done <\/p>\n<p>cp -r dir2\/ dir1\/ <\/p>\n<p>Copy file1 from dir1 to dir2 but prompt before overwrite:<\/p>\n<p>cp -i dir1\/file1 dir2\/ <\/p>\n<p>Copy file1 from dir1 to dir2 but prompt before overwrite:<\/p>\n<p>cp -i dir1\/file1 dir2\/ <\/p>\n<p>Link command <\/p>\n<p>HARD LINK  :It is copy of the old file to new file if the source file is deleted still we can have the  use link file <\/p>\n<p>ln  old new <\/p>\n<p>ln with soft link<\/p>\n<p>SOFT LINK :It is copy of the old file to  if the source file is deleted we wil lose the new link as well.<\/p>\n<p>ln -s old old_soft<\/p>\n<p>rm old   <\/p>\n<p>cat old_soft<br \/>\nerror doesnt exist <\/p>\n<p>=========================================================================================================================<br \/>\nFile Permissions list files ls<\/p>\n<p>chmod 775<br \/>\numask<\/p>\n<p>ls <\/p>\n<p>ls -d<\/p>\n<p>ls -l<\/p>\n<p>=====================================================================================================================================<br \/>\nuname -a <\/p>\n<p>#!\/bin\/sh<\/p>\n<p>SYSTEM=`uname -s`<br \/>\nif [ $SYSTEM = &#8220;Linux&#8221; ] ; then<br \/>\necho &#8220;Linux&#8221;<br \/>\nelif [ $SYSTEM = &#8220;FreeBSD&#8221; ] ; then<br \/>\necho &#8220;FreeBSD&#8221;<br \/>\nelif [ $SYSTEM = &#8220;Solaris&#8221; ] ; then<br \/>\necho &#8220;Solaris&#8221;<br \/>\nelse<br \/>\necho &#8220;What?&#8221;<br \/>\nfi   <\/p>\n<p>#system info<br \/>\nsystem_info() {<br \/>\necho &#8220;**********************************************&#8221;<br \/>\necho &#8220;system info:&#8221;<br \/>\necho<br \/>\necho &#8221;   System-release : `cat \/etc\/redhat-release`&#8221;<br \/>\necho &#8221;   Kernel-release : `uname -a|awk &#8216;{print $1,$3}&#8217;`&#8221;<br \/>\necho &#8221;   Server-Model : `dmidecode | grep &#8220;Product Name:&#8221;|sed -n &#8216;1p&#8217;|awk -F&#8217;: &#8216; &#8216;{print $2}&#8217;`&#8221;<br \/>\necho<br \/>\n} <\/p>\n<p>fn_distro(){<br \/>\narch=$(uname -m)<br \/>\nkernel=$(uname -r)<br \/>\nif [ -f \/etc\/lsb-release ]; then<br \/>\n        os=$(lsb_release -s -d)<br \/>\nelif [ -f \/etc\/debian_version ]; then<br \/>\n        os=&#8221;Debian $(cat \/etc\/debian_version)&#8221;<br \/>\nelif [ -f \/etc\/redhat-release ]; then<br \/>\n        os=`cat \/etc\/redhat-release`<br \/>\nelse<br \/>\n        os=&#8221;$(uname -s) $(uname -r)&#8221;<br \/>\nfi<br \/>\n} <\/p>\n<p> #!\/bin\/bash<br \/>\nfn_distro(){<br \/>\narch=$(uname -m)<br \/>\nkernel=$(uname -r)<br \/>\nif [ -f \/etc\/lsb-release ]; then<br \/>\n        os=$(lsb_release -s -d)<br \/>\nelif [ -f \/etc\/debian_version ]; then<br \/>\n        os=&#8221;Debian $(cat \/etc\/debian_version)&#8221;<br \/>\nelif [ -f \/etc\/redhat-release ]; then<br \/>\n        os=`cat \/etc\/redhat-release`<br \/>\nelse<br \/>\n        os=&#8221;$(uname -s) $(uname -r)&#8221;<br \/>\nfi<br \/>\n}<\/p>\n<p>fn_uptime(){<br \/>\nuptime=$(<br \/>\n===================================================================================================================<\/p>\n<p>Count Lines, Words &#038; Characters Using &#8216;wc&#8217;<\/p>\n<p>$ cat sample.txt<br \/>\ntoday is a<br \/>\ngood day<\/p>\n<p>$ wc -w sample.txt<br \/>\n5 sample.txt<\/p>\n<p>time perl -nle &#8216;$word += scalar(split(&#8221; &#8220;, $_)); END{print $word}&#8217; subst.c<\/p>\n<p>real    0m0.021s<br \/>\nuser    0m0.016s<br \/>\nsys     0m0.004s<\/p>\n<p>wc -l : Prints the number of lines in a file.<br \/>\nwc -w : prints the number of words in a file.<br \/>\nwc -c : Displays the count of bytes in a file.<br \/>\nwc -m : prints the count of characters from a file.<br \/>\nwc -L : prints only the length of the longest line in a file.<br \/>\n===================================================================================================================<br \/>\nsort <\/p>\n<p>cat > animals<br \/>\nowls<br \/>\ncamels<br \/>\npigs<br \/>\ndogs<br \/>\nlions<br \/>\nelephants<br \/>\nasses<\/p>\n<p>ctrl D<\/p>\n<p>base ball<br \/>\n[root@cluster1 tmp]# sort animals<br \/>\nasses<br \/>\ncamels<br \/>\ndogs<br \/>\nelephants<br \/>\nlions<br \/>\nowls<br \/>\npigs<br \/>\n[root@cluster1 tmp]# sort sports<br \/>\nbase ball<br \/>\ncricket<br \/>\nice hockey<br \/>\nsoccer<\/p>\n<p>$ cat test<br \/>\nzzz<br \/>\nsss<br \/>\nqqq<br \/>\naaa<br \/>\nBBB<br \/>\nddd<br \/>\nAAA<\/p>\n<p>sort test <\/p>\n<p>Create the following test file for this example:<\/p>\n<p>$ cat test<br \/>\n2K<br \/>\n2G<br \/>\n1K<br \/>\n6T<br \/>\n1T<br \/>\n1G<br \/>\n2M<br \/>\nThe following sort command sorts human readable numbers (i.e 1K = 1 Thousand, 1M = 1 Million, 1G = 1 Giga, 1T = 1 Tera) in test file and displays sorted output.<\/p>\n<p>$ sort -h test<br \/>\n1K<br \/>\n2K<br \/>\n2M<br \/>\n1G<br \/>\n2G<br \/>\n1T<br \/>\n6T<br \/>\n3. Sort Months of an Year using -M option<\/p>\n<p>If we want to sort in the order of months of year, then we can use -M or \u2013month-sort option.<\/p>\n<p>Create the following test file for this example:<\/p>\n<p>$ cat test<br \/>\nsept<br \/>\naug<br \/>\njan<br \/>\noct<br \/>\napr<br \/>\nfeb<br \/>\nmar11<br \/>\nThe following sort command sorts lines in test file as per month order. Note, lines in file should contain at least 3 character name of month name at start of line (e.g. jan, feb, mar). If we will give, ja for January or au for August, then sort command would not consider it as month name.<\/p>\n<p>$ sort -M test<br \/>\njan<br \/>\nfeb<br \/>\nmar11<br \/>\napr<br \/>\naug<br \/>\nsept<br \/>\noct<br \/>\n4. Check if Content is Already Sorted using -c option<\/p>\n<p>If we want to check data in text file is sorted or not, then we can use -c or \u2013check, \u2013check=diagnose-first option.<\/p>\n<p>Create the following test file for this example:<\/p>\n<p>$ cat test<br \/>\n2<br \/>\n5<br \/>\n1<br \/>\n6<br \/>\nThe following sort command checks whether text file data is sorted or not. If it is not, then it shows first occurrence with line number and disordered value.<\/p>\n<p>$ sort -c test<br \/>\nsort: test:3: disorder: 1<br \/>\n5. Reverse the Output and Check for Uniqueness using -r and -u options<\/p>\n<p>If we want to get sorted output in reverse order, then we can use -r or \u2013reverse option. If file contains duplicate lines, then to get unique lines in sorted output, \u201c-u\u201d option can be used.<\/p>\n<p>Create the following test file for this example:<\/p>\n<p>$ cat test<br \/>\n5<br \/>\n2<br \/>\n2<br \/>\n1<br \/>\n4<br \/>\n4<br \/>\nThe following sort command sorts lines in test file in reverse order and displays sorted output.<\/p>\n<p>$ sort -r test<br \/>\n5<br \/>\n4<br \/>\n4<br \/>\n2<br \/>\n2<br \/>\n1<br \/>\nThe following sort command sorts lines in test file in reverse order and removes duplicate lines from sorted output.<\/p>\n<p>$ sort -r -u test<br \/>\n5<br \/>\n4<br \/>\n2<br \/>\n1<br \/>\n6. Selectively Sort the Content, Customize delimiter, Write output to a file using  -k, -t, -o options<\/p>\n<p>If we want to sort on the column or word position in lines of text file, then \u201c-k\u201d option can be used. If we each word in each line of file is separated by delimiter except \u2018space\u2019, then we can specify delimiter using \u201c-t\u201d option. We can get sorted output in any specified output file (using \u201c-o\u201d option) instead of displaying output on standard output.<\/p>\n<p>Create the following test file for this example:<\/p>\n<p>$ cat test<br \/>\naa aa zz<br \/>\naa aa ff<br \/>\naa aa tt<br \/>\naa aa kk<br \/>\nThe following sort command sorts lines in test file on the 3rd word of each line and displays sorted output.<\/p>\n<p>$ sort -k3 test<br \/>\naa aa ff<br \/>\naa aa kk<br \/>\naa aa tt<br \/>\naa aa zz<br \/>\n$ cat test<br \/>\naa|5a|zz<br \/>\naa|2a|ff<br \/>\naa|1a|tt<br \/>\naa|3a|kk<br \/>\nHere, several options are used altogether. In test file, words in each line are separated by delimiter \u2018|\u2019. It sorts lines in test file on the 2nd word of each line on the basis of numeric value and stores sorted output into specified output file.<\/p>\n<p>$ sort -n -t&#8217;|&#8217; -k2 test -o outfile<br \/>\nThe contents of output file are shown below.<\/p>\n<p>$ cat outfile<br \/>\naa|1a|tt<br \/>\naa|2a|ff<br \/>\naa|3a|kk<br \/>\naa|5a|zz<\/p>\n<p>sort -r filename.txt<\/p>\n<p>Example6: Some times its required to sort the file and display only uniq values.<\/p>\n<p>sort -u filename<\/p>\n<p>Note: though the values on other field are different this will not consider by -u option.<\/p>\n<p>Example7: I want to sort a file according to my requirement and save it to a different file. Use -o option to save the sorted output to a file.<\/p>\n<p>sort -o temp.txt filename.txt<\/p>\n<p>Example8: Do you have file content with sizes like 10K, 20G, 45M, 32T etc. You can sort accourding to human readable by using -h option. This option works RHEL5 and above versions.<\/p>\n<p>sort -h filename.txt<\/p>\n<p>Similar to above example we can use -m for sorting according to month of the year.<\/p>\n<p>sort -M filename.txt<\/p>\n<p>Example9: Check if the file is alrady in sorted format or not by using -c option. This option will show you what is the first occurence disorderd value.<\/p>\n<p>sort -c filename.txt<\/p>\n<p>You can now mix above options to get your sorting work done.<\/p>\n<p>There are two types of sorting keys definition in Unix sort:<\/p>\n<p>new (with -k option)<br \/>\nold (+n -n).<\/p>\n<p>New-style sort keys definitions<\/p>\n<p>New style definition use -k option:<br \/>\n-k field_start [type] [,field_end [type] ]<\/p>\n<p>where:<br \/>\nfield_start and field_end<br \/>\ndefine a key field restricted to a portion of the line.<\/p>\n<p>type<br \/>\nis a modifier from the list of characters bdfiMnr. The b modifier behaves like the -b option, but applies only to the field_start or field_end to which it is attached and characters within a field are counted from the first non-blank character in the field. (This applies separately to first_character and last_character.) The other modifiers behave like the corresponding options, but apply only to the key field to which they are attached. They have this effect if specified with field_start, field_end or both. If any modifier is attached to a field_start or to a field_end, no option applies to either.<\/p>\n<p>When there are multiple key fields, later keys are compared only after all earlier keys compare equal. Except when the -u option is specified, lines that otherwise compare equal are ordered as if none of the options -d, -f, -i, -n or -k were present (but with -r still in effect, if it was specified) and with all bytes in the lines significant to the comparison.<\/p>\n<p>The notation:<br \/>\n-k field_start[type][,field_end[type]]<\/p>\n<p>defines a key field that begins at field_start and ends at field_end inclusive, unless field_start falls beyond the end of the line or after field_end, in which case the key field is empty. A missing field_end means the last character of the line.<br \/>\nA field comprises a maximal sequence of non-separating characters and, in the absence of option -t, any preceding field separator.<\/p>\n<p>The field_start portion of the keydef option-argument has the form:<\/p>\n<p>field_number[.first_character]<\/p>\n<p>Fields and characters within fields are numbered starting with 1. field_number and first_character, interpreted as positive decimal integers, specify the first character to be used as part of a sort key. If .first_character is omitted, it refers to the first character of the field.<\/p>\n<p>The field_end portion of the keydef option-argument has the form:<\/p>\n<p>field_number[.last_character]<\/p>\n<p>The field_number is as described above for field_start. last_character, interpreted as a non-negative decimal integer, specifies the last character to be used as part of the sort key. If last_character evaluates to zero or .last_character is omitted, it refers to the last character of the field specified by field_number.<\/p>\n<p>If the -b option or b type modifier is in effect, characters within a field are counted from the first non-blank character in the field. (This applies separately to first_character and last_character.)<\/p>\n<p>Old-style keys definition<br \/>\nThere is also &#8220;old-style&#8221; key definition[+pos1 [-pos2]] that are now formally obsolite, but still is extremly widely used. Provide functionality equivalent to the -kkeydef option.<\/p>\n<p>pos1 and pos2 each have the form m.n optionally followed by one or more of the flags bdfiMnr. A starting position specified by +m.n is interpreted to mean the n+1st character in the m+1st field. A missing .n means .0, indicating the first character of the m+1st field. If the b flag is in effect n is counted from the first non-blank in the m+1st field; +m.0b refers to the first non-blank character in the m+1st field.<\/p>\n<p>A last position specified by -m.n is interpreted to mean the nth character (including separators) after the last character of the mth field. A missing .n means .0, indicating the last character of the mth field. If the b flag is in effect n is counted from the last leading blank in the m+1st field; -m.1b refers to the first non-blank in the m+1st field.<\/p>\n<p>The fully specified +pos1 -pos2 form with type modifiers T and U: +w.xT -y.zU<\/p>\n<p>is equivalent to:<\/p>\n<p>undefined (z==0 &#038; U contains b &#038; -t is present)<br \/>\n-k w+1.x+1T,y.0U (z==0 otherwise)<br \/>\n-k w+1.x+1T,y+1.zU (z > 0)<\/p>\n<p>Implementations support at least nine occurrences of the sort keys (the -k option and obsolescent +pos1 and -pos2) which are significant in command line order. If no sort key is specified, a default sort key of the entire line is used.<\/p>\n<p>If the ordering rule options precede the sort key options, they are globally applied to all sort keys. For example, sort -r +2 -3 infile<br \/>\nreverses the order based on field 3. If the ordering rule options are attached to a sort key option, they override the global ordering options for only that sort key. For example,<\/p>\n<p>sort -r +2d -3d infile<\/p>\n<p>sorts field 3 by dictionary comparison but sorts the rest of the line using reverse comparison.<\/p>\n<p>The most common mistake is to forget to use -n option for sorting numeric fields. Also specifying delimiter (option -t) with an unquoted character after it can be a source of problems; it&#8217;s better to use single quotes around the character that you plan to use as a delimiter. for example -t &#8216;:&#8217;<\/p>\n<p>The most common mistake is to forget to use -n option for sorting numeric fields<\/p>\n<p>Here is a standard example of usage of the sort utility, sorting \/etc\/passwd file (user database) by UID (the third colon-separated field in the passwd file structure):<\/p>\n<p>sort -t &#8216;:&#8217; +2 \/etc\/passwd # incorrect result, the field is numeric<br \/>\nsort -n -t &#8216;:&#8217; +2 \/etc\/passwd # order of the numbers is now correct<\/p>\n<p>sort -t &#8216;:&#8217; -k 3,3n \/etc\/passwd<br \/>\nsort -t &#8216;:&#8217; +2 -3n \/etc\/passwd<br \/>\nsort -n -t &#8216;:&#8217; -k 3,3 \/etc\/passwd<\/p>\n<p>See Sorting key definitions and Examples for more details. Generally you will be surprised how often the result is not what you want due to the obscurity of the definitions<\/p>\n<p>Be careful and always test your sorting keys on a small sample before sorting the whole file. You will be surprised how often the result is not what you want.<\/p>\n<p>By default sort sorts the file in ascending order using the entire line as a sorting key. Please note that a lot of WEB resources interpret this sort utility behavior incorrectly (most often they state that by default sorting is performed on the first key).<\/p>\n<p>The three most important options of Unix soft are -n (numeric keys sorting), +n (sorting using n-th field, counting from zero) and -r (sort in reverse). For example:<br \/>\nSort the entire lines as a key: sort<br \/>\nSort in numeric order: sort -n<br \/>\nSort on n+1 st field (old style key definition): sort +n<\/p>\n<p>Comparisons are based on one or more sort keys extracted from each line of input. Again, please remember that by default, there is one sort key, the entire input line.<\/p>\n<p>Lines are ordered according to the collating sequence of the current locale. By changing locale you can change the behavior of the sort.<\/p>\n<p>In Solaris there are two variants of sort: System V version and BSD version. Both have identical options:<\/p>\n<p>\/usr\/bin\/sort [ -cmu ] [ -o output ] [ -T directory ] [ -y [ kmem ]] [ -z recsz ] [ -dfiMnr ] [ &#8211; b ] [ t char ] [ -k keydef ] [ +pos1 [ -pos2 ]] [ file&#8230;] <\/p>\n<p>\/usr\/xpg4\/bin\/sort [ -cmu ] [ -o output ] [ -T directory ] [ -y [ kmem ]] [ -z recsz ] [ &#8211; dfiMnr ] [ -b ] [ -t char ] [ -k keydef ] [ +pos1 [ -pos2 ]] [ file&#8230;]<\/p>\n<p>The sort command can (and should) be used in pipes or have its output redirected as desired. Here are some practically important examples that illustrates using of this utility (for more examples please look into our sort examples collection page): <\/p>\n<p>1. Sort the file and display the sorted file, one page at a time. (If you prefer the standard command &#8220;more&#8221;, you can use this instead of &#8220;less&#8221;. &#8220;less&#8221; is an enhanced version of &#8220;more&#8221; &#8211; for example, it allows you to move backwards and forwards in the file; to exit &#8220;less&#8221; , use &#8220;q&#8221;.)<br \/>\nsort file less <\/p>\n<p>2. Read and sorts infile and display the result on standard output, which has been redirected to outfile:<\/p>\n<p>sort infile > outfile # sorts infile and writes the results to outfile <\/p>\n<p>3. Write sorted output directly to outfile.<\/p>\n<p>sort -o outfile infile # same as in 1, but using an option -o <\/p>\n<p>4. Read and sort infile &#8220;in place&#8221; writing to the same file<\/p>\n<p>sort -o infile infile # sort file &#8220;in place&#8221; <\/p>\n<p>5. Sort the file and pipe it to uniq command with the number of identical keys counter printed (-c option in uniq)<\/p>\n<p>sort infile uniq -c <\/p>\n<p>6. Pipe the output of the who command to the input of the sort command:<\/p>\n<p>who sort <\/p>\n<p>7. Classic &#8220;number of instances&#8221; analysis of log files:<\/p>\n<p>cat messages awk &#8216;{&#8220;select the keywords&#8221;}&#8217; sort uniq -c sort -nr<\/p>\n<p>In simple cases cut can be used instead of AWK. For example the following example couts distinc visitors from HTTP logs (assuming this is the first field in the logs):<\/p>\n<p>cat http.log cut -d &#8221; &#8221; -f 1 sort uniq -c sort -nr <\/p>\n<p>8. Sort the file, then prepend line numbers to each line (not many Unix adminitrators know that cat can be used to number lines):<\/p>\n<p>sort -n file cat -n<\/p>\n<p>This can be useful if you want to count the number of lines in which the first entry is in a given range: simply subtract the line numbers corresponding to the beginning and end of the range. <\/p>\n<p>As I mentioned about by default the sort command uses entire lines as a key. It compares the characters starting with the first, until non-matching character or the end of the shortest line. Leading blanks (spaces and tabs) are considered valid characters to compare. Thus a line beginning with a space precedes a line beginning with the letter A. If you do not want this effect you need to delete leading spaces beforehand. <\/p>\n<p>Multiple sort keys may be used on the same command line. If two lines have the same value in the same field, sort uses the next set of sort keys to resolve the equal comparison. For example,<\/p>\n<p>sort +4 -5 +1 -2 infile<\/p>\n<p>means to sort based on field 5 (+4 -5). If two lines have the same value in field 5, sort those two lines based on field 2 (+1 -2).<\/p>\n<p>Beside sorting Unix sort is useful for merging files (option -m). It can also checked whether the file is sorted or not (option -c). It can also suppress duplicates (option -u):<\/p>\n<p>-c Check whether the given files are already sorted: if they are not all sorted, print an error message and exit with a status of 1.<\/p>\n<p>-m Merge the given files by sorting them as a group. Each input file should already be individually sorted. It always works to sort instead of merge; merging is provided because it is faster, in the case where it works.<\/p>\n<p>-u Suppress all but one occurrence of matching keys.<\/p>\n<p>In case Unix sort does not produce the required results you might want to look into Perl built-in function. If it is too slow more memory can be specified on invocation.<\/p>\n<p>The most important options<\/p>\n<p>The following list describes the options and their arguments that may be used to control how sort functions.<\/p>\n<p>&#8211; Forces sort to read from the standard input. Useful for reading from pipes and files simultaneously.<\/p>\n<p>-c Verifies that the input is sorted according to the other options specified on the command line. If the input is sorted correctly then no output is provided. If the input is not sorted then sort informs you of the situation. The message resembles this.<\/p>\n<p>sort: disorder: This line not in sorted order.<\/p>\n<p>-m Merges the sorted input. sort assumes the input is already sorted. sort normally merges input as it sorts. This option informs sort that the input is already sorted, thus sort runs much faster.<\/p>\n<p>-o output Sends the output to file output instead of the standard output. The output file may be the same name as one of the input files.<\/p>\n<p>-u Suppress all but one occurrence of matching keys. Normally, the entire line is the key. If field or character keys are specified, then the suppressing is done based on the keys.<\/p>\n<p>-y kmem Use kmem kilobytes of main memory to initially start the sorting. If more memory is needed, sort automatically requests it from the operating system. The amount of memory allocated for the sort impacts the speed of the sort significantly. If no kmem is specified, sort starts with the default amount of memory (usually 32K). The maximum (usually 1 Megabyte) amount of memory may be allocated if needed. If 0 is specified for kmem, the minimum (usually 16K) amount of memory is allocated.<\/p>\n<p>-z recsz Specifies the record size used to store each line. Normally the recsz is set to the longest line read during the sort phase. If the -c or -m options are specified, the sort phase is not performed and thus the record size defaults to a system size. If this default size is not large enough, sort may abort during the merge phase. To alleviate this problem you can specify a recsz that will allow the merge phase to run without aborting.<\/p>\n<p>Ordering Options<\/p>\n<p>-d Specifies dictionary sort. Only blanks, digits, and alphabetic characters are significant in the comparison.<\/p>\n<p>-f Fold lowercase letters to uppercase. Ignores the difference between upper and lowercase ASCII characters.<\/p>\n<p>-i Ignore characters outside the ASCII range of 040 (octal) and 0176 (octal). Only alphabetic characters, blanks, digits, and punctuation are used for comparison (printable characters). Control characters are ignored. This is only valid for nonnumeric sorts.<\/p>\n<p>-M Compare fields as months. The first three nonblank characters are folded (see -i option) to uppercase and compared. Thus January is compared as JAN. JAN precedes FEB, and fields not containing months precede JAN. The -b option is placed in effect automatically.<\/p>\n<p>-n Sorts the input numerically. The comparison is based on numerical value instead of alphabetic value. The number field used for comparison can contain optional blanks, optional minus signs, optional decimal point, and zero or more digits. The -b option is placed in effect automatically. Exponential numbers are not sorted correctly.<\/p>\n<p>-r Reverse the order of the output.<\/p>\n<p>Old-style Sort Key Options<\/p>\n<p>+pos1<br \/>\nSpecifies the beginning position of the input line used for field comparison. If pos1 is not specified then comparison begins at the beginning of the line. The pos1 position has the notation of f.c. The f specifies the number of fields to skip. The c specifies the number of characters to skip. For example, 3.2 is interpreted as skip three fields and two characters before performing comparisons. Omitting the .c portion is equivalent to specifying .0. Field one is referred to as position 0. If f is set to 0 then character positions are used for comparison.<\/p>\n<p>-pos2<br \/>\nSpecifies the ending position of the input line used for field comparison. If pos2 is not specified then comparison is done through the end of the line. The pos2 position has the notation of f.c. The f specifies to compare through field f. The c specifies the number of characters to compare through after field f. For example, -4.3 is interpreted as compare through three characters after the end of field four. Omitting the .c portion is equivalent to specifying .0.<\/p>\n<p>-b<br \/>\nIgnores leading blanks when using the restricted sort key positions (+pos1 and -pos2). If the -b option is placed before the first +pos1 argument, then it applies to all +pos1 arguments. The -b option can be attached to each pos string to affect only that field.<\/p>\n<p>-t c<br \/>\nUse character c as the field separator. Multiple adjacent c&#8217;s in the records are interpreted empty fields surrounded by separators. If you need to use multiple characters as a separator you need to convert record so that they are represented by a single character using sed or AWK. You can use nonprintable characters as a separator to ensure their uniqueness.<\/p>\n<p>Old News \ud83d\ude09<br \/>\n[Jul 14, 2007] My SysAd Blog &#8212; UNIX Sort Files by Their Filesizes<br \/>\nHere&#8217;s a convenient way of finding those space hogs in your home directory (can be any directory). For me, those large files are usually a result of mkfile event (testing purposes) and can be promptly deleted. Here&#8217;s an example of its use.<\/p>\n<p>#cd \/export\/home\/esofthub<br \/>\n#ls -l sort +4n awk &#8216;{print $5 &#8220;\\t&#8221; $9}&#8217;<\/p>\n<p>Find recursively (a little awkward)<br \/>\n#ls -lR sort +4n awk &#8216;{print $5 &#8220;\\t&#8221; $9}&#8217; more<\/p>\n<p>ps -ef sort<\/p>\n<p>This command pipeline sorts the output of the &#8220;ps -ef&#8221; command. Because no arguments are supplied to the sort command, the output is sorted in alphabetic order by the first column of the ps -ef output (i.e., the output is sorted alphabetically by username).<\/p>\n<p>ls -al sort +4n<\/p>\n<p>This command performs a numeric sort on the fifth column of the &#8220;ls -al&#8221; output. This results in a file listing where the files are listed in ascending order, from smallest in size to largest in size.<\/p>\n<p>ls -al sort +4n more<\/p>\n<p>The same command as the previous, except the output is piped into the more command. This is useful when the output will not all fit on one screen.<\/p>\n<p>ls -al sort +4nr<\/p>\n<p>This command reverses the order of the numeric sort, so files are listed in descending order of size, with the largest file listed first, and the smallest file listed last.<\/p>\n<p>[Feb 15, 2007] UNIX Disk Usage Simplifying Analysis with sort<br \/>\nThe output of du has been very informative, but it&#8217;s difficult to scan a listing to ascertain the four or five largest directories, particularly as more and more directories and files are included in the output. The good news is that the Unix sort utility is just the tool we need to sidestep this problem.<br \/>\n# du -s * sort -nr<br \/>\n13984 Lynx<br \/>\n10464 IBM<br \/>\n3092 Gator<br \/>\n412 bin<br \/>\n196 DEMO<br \/>\n84 etcpasswd<br \/>\n76 CBO_MAIL<br \/>\n48 elance<br \/>\n36 CraigsList<br \/>\n16 Exchange<br \/>\n4 gettermsheet.sh<br \/>\n4 getstocks.sh<br \/>\n4 getmodemdriver.sh<br \/>\n4 buckaroo<br \/>\n4 browse.sh<br \/>\n4 badjoke.rot13<br \/>\n4 badjoke<br \/>\n0 gif.gif<\/p>\n<p>One final concept and we&#8217;re ready to move along. If you want to only see the five largest files or directories in a specific directory, all that you&#8217;d need to do is pipe the command sequence to head:<\/p>\n<p># du -s * sort -nr head -5<br \/>\n13984 Lynx<br \/>\n10464 IBM<br \/>\n3092 Gator<br \/>\n412 bin<br \/>\n196 DEMO<\/p>\n<p>The ! command (pronounced &#8220;bang&#8221;) creates a temporary file to be used with a program that requires a filename in its command line. This is useful with shells that don&#8217;t support process substitution. For example, to diff two files after sorting them, you might do:<\/p>\n<p>diff `! sort file1` `! sort file2`<\/p>\n<p>This command pipeline sorts the output of the &#8220;ps -ef&#8221; command. Because no arguments are supplied to the sort command, the output is sorted in alphabetic order by the first column of the ps -ef output (i.e., the output is sorted alphabetically by username).<\/p>\n<p>ls -al sort +4n<\/p>\n<p>This command performs a numeric sort on the fifth column of the &#8220;ls -al&#8221; output. This results in a file listing where the files are listed in ascending order, from smallest in size to largest in size.<\/p>\n<p>ls -al sort +4n more<\/p>\n<p>The same command as the previous, except the output is piped into the more command. This is useful when the output will not all fit on one screen.<\/p>\n<p>ls -al sort +4nr<\/p>\n<p>This command reverses the order of the numeric sort, so files are listed in descending order of size, with the largest file listed first, and the smallest file listed last.<br \/>\n======================================================================================================================================<\/p>\n<p>Cut Command<\/p>\n<p>Linux command cut is used for text processing. You can use this command to extract portion of text from a file by selecting columns.<\/p>\n<p>Cutting specific fileds<br \/>\nComma as Delimiter<br \/>\nSpace as Delimiter<br \/>\nPipe as Delimiter<br \/>\nCutting from first field<br \/>\nCutting till last field<br \/>\nCutting range of fields<br \/>\nIgnore lines without delimiter<br \/>\nInvert field selection<br \/>\nSpecify output delimiter<br \/>\nCut specified characters<br \/>\nCut specified bytes<\/p>\n<p>-c, &#8211;characters=LIST<br \/>\n                       select only these characters<br \/>\n-d, &#8211;delimiter=DELIM<br \/>\n                       use DELIM instead of TAB for field delimiter<br \/>\n-f, &#8211;fields=LIST<br \/>\n                       select  only  these fields;  also print any line that contains no delimiter character, unless the -s option is specified<br \/>\n-s, &#8211;only-delimited<br \/>\n                       do not print lines not containing delimiters<\/p>\n<p>The cut command, as the man page states, \u201cremoves sections from each line of a file.\u201d  The cut command can also be used on a stream and it can do more than just remove section.  If a file is not specified or \u201c-\u201d is used  the cut command takes input from standard in.  The cut command can be used to extract sections from a file or stream based upon a specific criteria.  An example of this would be cutting specific fields from a csv (comma separated values) file.  For instance, cut can be used to extract the name and email address from a csv file with the following content:<\/p>\n<p>id, date, username, first name, last name, email address, phone, fax<br \/>\n1,2012-01-01,franklinf, Ford, Franklin, ff@gmail.com, 7575551212, 7775551234<br \/>\n2,2012-02-01,levona, Allan, Levon, allanl@tllts.org, 3177771212,<br \/>\n3,2012-02-17,mannyt,  Trish, Manny, tmanny@hpr.org,7275551212,8885551236<\/p>\n<p>he syntax for cut would be:<\/p>\n<p>cut -d\u201d,\u201d -f4,5,6 users.csv<\/p>\n<p>The result would be displayed on standard out:<\/p>\n<p>first name, last name, email address<br \/>\nFord, Franklin, ff@gmail.ccom<br \/>\nAllan, Levon, allanl@tllts.org<br \/>\nTrish, Manny, tmanny@hpr.org<\/p>\n<p>The -d option specifies the delimiter which is defaults to a TAB.   In the example above the cut command will \u201ccut\u201d the line at each \u201c,\u201d instead of a TAB.  The -f option indicates which fields to select, in this case fields 4, 5, and 6 which correspond to \u201cfirst name,\u201d \u201clast name,\u201d and \u201cemail address.\u201d<\/p>\n<p>The cut command can operate on fields, characters or bytes and must include one and only one of these options.<\/p>\n<p>The field option operates on the cuts defined by the delimiter (-d), which is TAB by default.  The -d option can only be used with the field option.  Attempting to use the -d option with the character (-c) or bytes (-b) options will result in an error.  The -f value can be a command separated list or a range separated by a \u201c-\u201c:<\/p>\n<p>cut -d\u201d,\u201d -f 1,2,3,4<br \/>\ncut -d\u201d,\u201d -f 1-4<br \/>\ncut -f 1-4,7,9<br \/>\ncut -d\u201d,\u201d -f -7<br \/>\ncut -d\u201d,\u201d -f 7-<\/p>\n<p> cut is a very frequently used command for file parsing. It is very useful in splitting columns on files with or without delimiter. In this article, we will see how to use the cut command on files having a delimiter.<\/p>\n<p>Let us consider a sample file, say file1, with a comma as delimiter as shown below:<br \/>\n$ cat file1<br \/>\nRakesh,Father,35,Manager<br \/>\nNiti,Mother,30,Group Lead<br \/>\nShlok,Son,5,Student<br \/>\n The first column indicates name, second relationship, the third being the age, and the last one is their profession.<\/p>\n<p>  cut command has 2 main options to work on files with delimiters:<\/p>\n<p> -f &#8211; To indicate which field(s) to cut.<br \/>\n -d &#8211; To indicate the delimiter on the basis of which the cut command will cut the fields.<\/p>\n<p>Let us now try to work with this command with a few examples:<\/p>\n<p>1. To get the list of names alone from the file, which is the first column:<br \/>\n$ cut -d, -f 1 file1<br \/>\nRakesh<br \/>\nNiti<br \/>\nShlok<br \/>\n   The option &#8220;-d&#8217; followed by a comma indicates to cut the file on the basis of comma. &#8220;-f&#8221; followed by 1 indicates to retrieve the field 1 from the file1, and hence we got the names alone.<\/p>\n<p>2. To get the relationship alone:, i.e, 2nd field<br \/>\n$ cut -d, -f 2 file1<br \/>\nFather<br \/>\nMother<br \/>\nSon<br \/>\n3.  To get 2 fields, say Name and Age:<br \/>\n$ cut -d, -f 1,3 file1<br \/>\nRakesh,35<br \/>\nNiti,30<br \/>\nShlok,5<br \/>\n   Giving 1,3 means to retrieve the first and third fields which happens to be name and age respectively.<\/p>\n<p>4. To get the name, relationship and age, excluding the profession, i.e, 1st to 3rd fields:<br \/>\n$ cut -d, -f 1-3 file1<br \/>\nRakesh,Father,35<br \/>\nNiti,Mother,30<br \/>\nShlok,Son,5<br \/>\n   The option 1-3 means from first field till third field. Whenever we need a range of fields to be retrieved, we use the &#8216;-&#8216; option.<\/p>\n<p> The same result above can also be retrieved in other ways also:<br \/>\n$ cut -d, -f -3 file1<br \/>\nRakesh,Father,35<br \/>\nNiti,Mother,30<br \/>\nShlok,Son,5<br \/>\nThis is the best of the 3 methods to retrieve a range of fields. The option &#8220;-3&#8221; means from the beginning i.e, the first field till the third field. And hence we get the fields 1, 2 and 3.<\/p>\n<p>5. To retrieve all the fields except the name field. i.e, to retrieve from field 2 to field 4:<br \/>\n$ cut -d, -f 2- file1<br \/>\nFather,35,Manager<br \/>\nMother,30,Group Lead<br \/>\nSon,5,Student<br \/>\n  Similar to the last result, &#8220;2-&#8221; means from the second field till the end which is the 4th field. Whenever the beginning of the range is not specified, it defaults to 1, similarly when the end of the range is not given, it defaults to the last field. The same result could have been achieved using the option &#8220;2-4&#8243; as well.<\/p>\n<p>Let us consider the same input file with a space as the delimiter:<br \/>\n$ cat file1<br \/>\nRakesh Father 35 Manager<br \/>\nNiti Mother 30 GL<br \/>\nShlok Son 5 Student<br \/>\n   The same options and commands used above hold good but for the delimiter specified. When comma is the delimiter, we can give it after the -d option. However, for the space as delimiter, we need to quote the delimiter as shown below. In fact, we can always quote the delimiter to be in the safer side.<\/p>\n<p>6. To retrieve the first field from a space delimited file:<br \/>\n$ cut -d&#8221; &#8221; -f 1 file1<br \/>\nRakesh<br \/>\nNiti<br \/>\nShlok<br \/>\nLet us consider the same file separated by tab space:<br \/>\n$ cat file1<br \/>\nRakesh  Father  35      Manager<br \/>\nNiti    Mother  30      GL<br \/>\nShlok   Son     5       Student<br \/>\n To actually confirm the file is indeed separated by tab space, use the &#8220;-t&#8221;  option with the cat command:<br \/>\n$ cat -t file1<br \/>\nRakesh^IFather^I35^IManager<br \/>\nNiti^IMother^I30^IGL<br \/>\nShlok^ISon^I5^IStudent<br \/>\n   The ^I indicates a tab space.<\/p>\n<p>7. To retrieve the first field from this tab separated file. How to specify the tab space with the &#8220;-d&#8221; option?<br \/>\n$ cut -f 1 file1<br \/>\nRakesh<br \/>\nNiti<br \/>\nShlok<\/p>\n<p>he options to cut by are below.<\/p>\n<p>N          N\u2019th byte, character or field, counted from 1<br \/>\nN-         from N\u2019th byte, character or field, to end of line<br \/>\nN-M      from N\u2019th to M\u2019th (included) byte, character or field<br \/>\n-M         from first to M\u2019th (included) byte, character or field<\/p>\n<p>The options pretty much explain themselves but I have included some simple examples below:<br \/>\nCutting by characters (command on top, output below)<\/p>\n<p>echo &#8220;123456789&#8221; | cut -c -5<br \/>\n12345<\/p>\n<p>echo &#8220;123456789&#8221; | cut -c 5-<br \/>\n56789<\/p>\n<p>echo &#8220;123456789&#8221; | cut -c 3-7<br \/>\n34567<\/p>\n<p>echo &#8220;123456789&#8221; | cut -c 5<br \/>\n5<\/p>\n<p>Sometimes output from a command is delimited so a cut by characters will not work. Take the example below:<\/p>\n<p>echo -e &#8220;1\\t2\\t3\\t4\\t5&#8221; |cut -c 5-7<br \/>\n3 4<\/p>\n<p>To echo a tab you have to use the -e switch to enable echo to process back slashed characters. If the desired output is 3\\t4 then this would work great if the strings were always 1 character but if anywhere before field 3 a character was added the output would be completely changed as followed:<\/p>\n<p>echo -e &#8220;1a\\t2b\\t3c\\t4d\\t5e&#8221; | cut -c 5-7<br \/>\nb 3<\/p>\n<p>This is resolved by cutting by fields.<br \/>\nCutting by fields<\/p>\n<p>The syntax to cut by fields is the same as characters or bytes. The two examples below display different output but are both displaying the same fields (Fields 3 Through to the end of line.)<\/p>\n<p>echo -e &#8220;1\\t2\\t3\\t4\\t5&#8221; | cut -f 3-<br \/>\n3 4 5<\/p>\n<p>echo -e &#8220;1a\\t2a\\t3a\\t4a\\t5a&#8221; | cut -f 3-<br \/>\n3a 4a 5a<\/p>\n<p>The default delimiter is a tab, if the output is delimited another way a custom delimiter can be specified with the -d option. It can be just about any printable character, just make sure that the character is escaped (back slashed) if needed. In the example below I cut the string up using the pipe as the delimiter.<\/p>\n<p>echo &#8220;1|2|3|4|5&#8221; | cut -f 3- -d \\|<br \/>\n3|4|5<\/p>\n<p>One great feature of cut is that the delimiter that was used for input can be changed by the output of cut. In the example below I change the format of the string from a dash delimited output and change it to a comma.<\/p>\n<p>echo -e &#8220;1a-2a-3a-4a-5a&#8221; | cut -f 3- -d \u2013 &#8211;output-delimiter=,<br \/>\n3a,4a,5a<\/p>\n<p>Formatting with Cut Example<\/p>\n<p>Sometimes certain Linux applications such as uptime do not have options to format the output. Cut can be used to pull out the information that is desired.<br \/>\nNormal up-time Command:<\/p>\n<p>root@cluster1 :~$ uptime<br \/>\n19:18:40 up 1 day, 22:15, 4 users, load average: 0.45, 0.10, 0.03<\/p>\n<p>Time with up-time displayed:<\/p>\n<p>root@cluster1 :~$ uptime |cut -d , -f 1,2 | cut -c 2-<br \/>\n19:19:36 up 1 day, 22:22<\/p>\n<p>For the above example I pipe the output of uptime to cut and tell it I want to split it with a comma , delimiter. I then choose fields 1 and 2. The output from that cut is piped into another cut that removes the spaces in front of the output.<br \/>\nLoad averages extracted from uptime:<\/p>\n<p>root@cluster1 :~$ uptime |cut -d , -f 4- | cut -c 3-<br \/>\nload average: 0.42, 0.10, 0.03<\/p>\n<p>This is about the same as the previous example except the fields changed. Instead of fields 1 and 2 I told it to display fields 4 through the end. The output from that is piped to another cut which removes the three spaces that were after the comma in &#8220;4 users, &#8221; by starting at the 3rd character.<br \/>\nThe great thing about cutting by fields is that no matter if the field length changes the data stays the same. Take the example below. I now have 17 users logged in which would have broke the output if I had used -c (since there is an extra character due to a double digit number of users being logged in.)<\/p>\n<p>root@cluster1 :~$ uptime<br \/>\n19:25:11 up 1 day, 22:28, 17 users, load average: 0.00, 0.06, 0.04<\/p>\n<p>root@cluster1 :~$ uptime |cut -d , -f 4- | cut -c 3-<br \/>\nload average: 0.00, 0.06, 0.04<\/p>\n<p>That just about covers everything for the cut command. Now you know about it you can use cut to chop up all types of strings. It is one of the many great tools available for string manipulation in bash. If you can remember what cut does it will make your shell scripting easier, you don\u2019t need to memorize the syntax because all of the information on how to use cut is available here, in the man pages and all over the web.<\/p>\n<p>========================================================================================================================================================================================================<br \/>\nConvert &#038; Copy Files With &#8216;dd&#8217;<\/p>\n<p>The Linux command \u2018dd\u2019 is one of the very powerful utility which can be used in a variety of ways. This tool is mainly used for copying and converting data, hence it stands for \u2018data duplicator\u2019.<\/p>\n<p>This tool can be used for.<\/p>\n<p>\u2022 Backing up and restoring an entire hard drive or a partition<\/p>\n<p>\u2022 Copy regions of raw device files like backing up MBR(master boot record)<\/p>\n<p>\u2022 Converting data formats like ASCII to EBCDIC<\/p>\n<p>\u2022 Converting lowercase to uppercase and vice versa<\/p>\n<p>\u2022 Creating files with fixed size<\/p>\n<p>Only superuser can execute this command. You should be very careful while using this command as improper usage may cause huge data loss. So, some people consider this tool as \u2018data destroyer\u2019.<\/p>\n<p>Syntax of \u2018dd\u2019 command<\/p>\n<p>dd  if=<source file name>of=<target file name> [Options]<\/p>\n<p>[root@cluster1 tmp]# cat doc<br \/>\nHi how are you and Now you know about it you can use cut to chop up all types of strings.<\/p>\n<p>[root@cluster1 tmp]# dd if=doc of=out conv=ucase<br \/>\n0+1 records in<br \/>\n0+1 records out<br \/>\n90 bytes (90 B) copied, 0.00021344 s, 422 kB\/s<\/p>\n<p>1. Backing up and restoring an entire hard drive or a partition<\/p>\n<p>a. Backup entire hard drive to another drive.<\/p>\n<p>dd if=\/dev\/sda of=\/dev\/sdb bs=4096 conv=noerror,sync<\/p>\n<p>Here, \u2018if\u2019 stands for input file , \u2018of\u2019 stands for output file and \u2018bs\u2019 stands for the block size (number of bytes to be read\/write at a time). The conversion parameter \u2018noerror\u2019 allows the tool to continue to copy the data eventhough it encounter any errors. The sync option allows to use synchronized I\/O.<\/p>\n<p>The above command will copy all the data from the disk \/dev\/sda to \/dev\/sdb. \u2018dd\u2019 doesn\u2019t know anything about the filesystem or partitions- it will just copy everything from \/dev\/sda to \/dev\/sdb. So, this will clone the disk with the same data on same partition.<\/p>\n<p>b. Creating a disk image<\/p>\n<p>dd if=\/dev\/sda of=\/tmp\/sdadisk.img<\/p>\n<p>Backing up a disk to an image will be faster than copying the exact data. Also, disk image make the restoration much more easier.<\/p>\n<p>c. Creating a compressed disk image<\/p>\n<p>dd if=\/dev\/sda | gzip >\/tmp\/sdadisk.img.gz<\/p>\n<p>d. Restoring hard disk image<\/p>\n<p>dd if=\/tmp\/sdadisk.img of=\/dev\/sda<\/p>\n<p>e. Restoring compressed image<\/p>\n<p>gzip \u2013dc \/tmp\/sdadisk.img.gz | dd of=\/dev\/sda<\/p>\n<p>f. Clone one partition to another<\/p>\n<p>dd if=\/dev\/sda1 of=\/dev\/sdb1 bs=4096 conv=noerror,sync<\/p>\n<p>This will synchronize the partition \/dev\/sda1 to \/dev\/sdb1. You must verify that the size of \/dev\/sdb1 should be larger than \/dev\/sda1<\/p>\n<p>2. Backing up and Restoring MBR<\/p>\n<p>Master Boot record is the boot sector which houses the GRUB boot loader. If MBR got corrupted, we will not be able to boot into Linux. MBR -512 byte data- is located at the first sector of the hard disk. It consists of 446 byte bootstrap, 64 byte partition table and 2 bytes signature.<\/p>\n<p>a. Backing up MBR<\/p>\n<p>dd if=\/dev\/sda of=\/tmp\/mbr.img bs=512 count=1<\/p>\n<p>The option \u201ccount\u201d refers to the number of input blocks to be copied<\/p>\n<p>b. Backing up the boot data of MBR excluding the partition table<\/p>\n<p>dd if=\/dev\/sda of=\/tmp\/mbr.img bs=446 count=1<\/p>\n<p>c. Restoring MBR from MBR image<\/p>\n<p>dd if=\/tmp\/mbr.img of=\/dev\/sda<\/p>\n<p>d. Display master boot record<\/p>\n<p>dd if=\/dev\/hda of=mbr.bin bs=512 count=1<br \/>\nod -xa mbr.bin<\/p>\n<p>3. Converting data formats<\/p>\n<p>a. Convert the data format of a file from ASCII to EBCDIC<\/p>\n<p>dd if=textfile.ascii of=textfile.ebcdic conv=ebcdic<\/p>\n<p>b. Convert the data format of a file from EBCDIC to ASCII<\/p>\n<p>dd if=textfile.ebcdic of=textfile.ascii conv=ascii<\/p>\n<p>4. Converting case of a file<\/p>\n<p>a. Converting a file to Uppercase<\/p>\n<p>dd if=file1 of=file2 conv=ucase<\/p>\n<p>b. Converting a file to lowercase<\/p>\n<p>dd if=file1 of=file2 conv=lcase<\/p>\n<p>5. Creating or modifying data files<\/p>\n<p>a. Create a fixed size, say 10MB file<\/p>\n<p>dd if=\/dev\/zero of=file1 bs=10485760 count=1<\/p>\n<p>The block size is calculated as 10MB=10*1024*1024<\/p>\n<p>b. Modify the first 512 bytes of a file with null data<\/p>\n<p>dd if=\/dev\/zero of=file1 bs=512 count=1 conv=notrunc<\/p>\n<p>The option \u2018notrunc\u2019 refers to do not truncate the file, only replace the first 512 bytes, if it exists. Otherwise, you will get a 512 byte file.<\/p>\n<p>Creating an image file with dd command<br \/>\nFirst, make sure you&#8217;ve sufficient disk space to create a image file using dd:<br \/>\n$ df -H<\/p>\n<p>To create 1MB file (1024kb), enter:<br \/>\n$ dd if=\/dev\/zero of=test.img bs=1024 count=0 seek=1024<\/p>\n<p>You will get an empty files (also known as &#8220;sparse file&#8221;) of arbitrary size using above syntax. To create 10MB file , enter:<br \/>\n$ dd if=\/dev\/zero of=test.img bs=1024 count=0 seek=$[1024*10]<\/p>\n<p>To create 100MB file , enter:<br \/>\n$ dd if=\/dev\/zero of=test.img bs=1024 count=0 seek=$[1024*100]<br \/>\n$ ls -lh test.img<\/p>\n<p>To create 1GB, file:<br \/>\n$ dd if=\/dev\/zero of=1g.img bs=1 count=0 seek=1G<br \/>\nSample output:<\/p>\n<p>0+0 records in<br \/>\n0+0 records out<br \/>\n0 bytes (0 B) copied, 0.000235686 s, 0.0 kB\/s<br \/>\nVerify file size (note bs factor in original dd command):<br \/>\n$ ls -lh 1g.img<br \/>\n$ stat 1g.img<br \/>\n$ du -h 1g.im<\/p>\n<p>Burn an ISO File<\/p>\n<p>Using the Terminal<\/p>\n<p>To burn the iso on an usb stick, enter the following command in a terminal :<br \/>\ndd bs=4M if=\/path\/to\/manjaro.iso of=\/dev\/sd[drive letter]<br \/>\nWhere [drive letter] is the letter of your removable device. Please note that it is the device (e.g. \/dev\/sdb), and not the partition number (e.g. \/dev\/sdb1).<br \/>\nTo find which drive letter it might be write:<br \/>\nfdisk -l<\/p>\n<p>============================================================================================================<\/p>\n<p>Get Help, View Fancy Text &#038; Reduce File Size<\/p>\n<p>man <\/p>\n<p>banner command <\/p>\n<p>How do I use figlet?<\/p>\n<p>Simply use it as follows:<br \/>\nfiglet &#8220;Shell Hacks&#8221;<br \/>\n ____  _          _ _   _   _            _<br \/>\n\/ ___|| |__   ___| | | | | | | __ _  ___| | _____<br \/>\n\\___ \\| &#8216;_ \\ \/ _ \\ | | | |_| |\/ _` |\/ __| |\/ \/ __|<br \/>\n ___) | | | |  __\/ | | |  _  | (_| | (__|   <\\__ \\\n|____\/|_| |_|\\___|_|_| |_| |_|\\__,_|\\___|_|\\_\\___\/\nTo change the font, use the -f option, for example :\n\n$ figlet -f digital \"Shell Hacks\"\n+-+-+-+-+-+ +-+-+-+-+-+\n|S|h|e|l|l| |H|a|c|k|s|\n+-+-+-+-+-+ +-+-+-+-+-+\nUse the -c option if you would prefer centered output :\n\n$ figlet -c \"Shell Hacks\"\n       _       _____            __ _\n      (_)     \/ ____|          \/ _| |\n _ __  ___  _| |     _ __ __ _| |_| |_\n| '_ \\| \\ \\\/ \/ |    | '__\/ _` |  _| __|\n| | | | |>  <| |____| | | (_| | | | |_\n|_| |_|_\/_\/\\_\\\\_____|_|  \\__,_|_|  \\__|\n\n\n======================================================================================================================\n\nProgramming 1 \n\n\nHello World\n\n\n\n[root@cluster1 shell]# cat test.sh\n#!\/bin\/bash\necho \"Hello World\"\n\n\n\necho -e \"\n##################################\n#\n# Welcome to `hostname`\n# This system is running `cat \/etc\/redhat-release`\n# kernel is `uname -r`\n#\n# You are logged in as `whoami`\n#\n##################################\n\"\n=========================================================================================================================\nShell Variables, Grab User Input Using 'read'\n\n===========================================================================================================================================================\n\n###########Positional Parameters###########\n\na=25\necho$a\n25\n\na=\"Hey, what's up\"\n\necho $a\n\n\n#!\/bin\/bash\necho \"please provide the arugument\"\nmv $1 $2\ncat $2\n\n\n#!\/bin\/bash\nchmod 744 $1\nls -l $1 \n\n\n\nset I love india\n\necho $1\n\necho $*\n\n\nReverse Quotes Or Accent Graves\n\n#!\/bin\/bash\nname=$1\nset `who am i `\nmv $name  $name.$1\n\n\n[root@cluster1 shell]# cat shell2.sh\necho i am not doing good while runing this shell program=$#\n\n[root@cluster1 shell]# .\/shell2.sh Count The Number of Command Line Arguments Using\ni am not doing good while runing this shell program=8\n\n==================================================================================================================================================================================\nMath On Integers Using 'expr'\n\n\n\nInteger Math\n\nFirst way to do math with integer (and only integer) is to use the command \u201cexpr \u2014 evaluate expression\u201d.\n\nroot@cluster1 $ expr 1 + 1\n2\nroot@cluster1 $ myvar=$(expr 1 + 1)\nroot@cluster1 $ echo $myvar\n2\nroot@cluster1 $ expr $myvar + 1\n3\nroot@cluster1 $ expr $myvar \/ 3\n1\nroot@cluster1 $ expr $myvar \\* 3\n9\nWhen doing a \u201cmultiply by\u201d make sure to backslash the \u201casterisk\u201d  as it\u2019s a wildcard in Bash used for expansion.\n\nAnother alternative to expr, is to use the bash builtin command let.\n\nroot@cluster1 $ echo $myvar\n6\nroot@cluster1 $ let myvar+=1\nroot@cluster1 $ echo $myvar\n7\nroot@cluster1 $ let myvar+1\nroot@cluster1 $ echo $myvar\n7\nroot@cluster1 $ let myvar2=myvar+1\nroot@cluster1 $ echo $myvar2\n8\nAlso, you can simply use the parentheses or square brackets :\n\nroot@cluster1 $ echo $myvar\n3\nroot@cluster1 $ echo $((myvar+2))\n5\nroot@cluster1 $ echo $[myvar+2]\n5\nroot@cluster1 $ myvar=$((myvar+3))\nThis allow you to use C-style programming :\n\nroot@cluster1 $ echo $myvar\n3\nroot@cluster1 $ echo $((myvar++))\n3\nroot@cluster1 $ echo $myvar\n4\nroot@cluster1 $ echo $((++myvar))\n5\nroot@cluster1 $ echo $myvar\n5\nFloating point arithmetic\n\nYou can\u2019t do floating point arithmetic natively in bash, you will have to use a command line tool, the most common one being \u201cbc - An arbitrary precision calculator language\u201d.\n\nroot@cluster1 $ bc\nbc 1.06\nCopyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc.\nThis is free software with ABSOLUTELY NO WARRANTY.\nFor details type `warranty'.\n3*5.2+7\/8\n15.6\n15.6+299.33*2.3\/7.4\n108.6\nOf course you can use the STDIN to send your formula to \u201cbc\u201d then get the output on STDOUT.\n\n\nroot@cluster1 $ echo \"3.4+7\/8-(5.94*3.14)\" | bc\n-15.25\nor by using the here-doc notation:\n\nroot@cluster1 $ bc <<< \"3.4+7\/8-(5.94*3.14)\"\n-15.25\nI encourage you too take a look at the man pages to get more detail on how it works (man bc).\n\nThere are four special variables, scale, ibase, obase, and last.  scale defines how some operations use digits after the decimal point.  The default value of scale is 0. ibase and obase define the conver-\nsion base for input and output numbers.  The default for both input and output is base 10.  last (an extension) is a variable that has the value of the last printed number.\nThe \u201cscale\u201d variable is really important for the precision of your results, especially when using integers only (Note: you can also use \u201cbc -l\u201d to use mathlib and see the result at max scale) .\n\n\n\nroot@cluster1 $ echo \"2\/3\" | bc\n0\nroot@cluster1 $ echo \"scale=2; 2\/3\" | bc\n.66\nroot@cluster1 $ echo \"(2\/3)+(7\/8)\" | bc\n0\nroot@cluster1 $ echo \"scale=2;(2\/3)+(7\/8)\" | bc\n1.53\nroot@cluster1 $ echo \"scale=4;(2\/3)+(7\/8)\" | bc\n1.5416\nroot@cluster1 $ echo \"scale=6;(2\/3)+(7\/8)\" | bc\n1.541666\nroot@cluster1 $ echo \"(2\/3)+(7\/8)\" | bc -l\n1.54166666666666666666\nAnother way to do floating point arithmetic is to use AWK:\n\nroot@cluster1 $ awk \"BEGIN {print 100\/3}\"\n33.3333\nYou can use printf to adjust the precision of the results:\n\n\nroot@cluster1 $ awk \"BEGIN {printf \\\"%.2f\\n\\\", 100\/3}\"\n33.33\nWhen using negative values, make sure to leave a white space between signs.\n\nWRONG\n\nroot@cluster1 $ awk \"BEGIN {print -8.4--8}\"\nawk: cmd. line:1: BEGIN {print -8.4--8}\nawk: cmd. line:1:                    ^ syntax error\nGOOD\n\nroot@cluster1 $ awk \"BEGIN {print -8.4 - -8}\"\n-0.4\n\n\n\n\n\n\n#!\/bin\/bash\na=30 b=30\necho `expr $a + $b`\necho `expr $a - $b`\necho `expr $a \\* $b`\necho `expr $a \/ $b`\necho `expr $a % $b`\n\n==================================================================================================================================================================================\nOperator Precedence\n\n\n1st preference  = \/, * , % \n2nd preference  = +, - \n\n#!\/bin\/bash\na=40 b=35 c=25  d=50\n\n#!\/bin\/bash\na=40 b=35 c=25  d=50\necho `expr $a \\* \\( $b + $c \\) \/ $d`\n\n==================================================================================================================================================================================\n\nMath On Real Numbers  Floating Point Arithmetic \n\nbc\n\n\n#!\/bin\/bash\na=2.5 b=3.5\nc=`echo $a + $b | bc`\nd=`echo $a - $b | bc`\nf=`echo $a \\* $b  | bc`\ng=`echo $a \/ $b   | bc`\necho $c, $d, $e, $f\n\n\n\n\n $ result=$(echo \"scale=2; 5 * 7 \/3;\" | bc)\n  $ echo $result\n  11.66\n  \necho 'scale=2; (2.777 - 1.4744)\/1' | bc \n1.30\n\nIn contrast, note that the bash shell only performs integer arithmetic, e.g.:\n  $ result=$((5 * 7 \/3))\n  $ echo $result\n  11\n  \nCommand substitution stores the output of a command into a variable.\nvar3=$(echo \"scale=2;$var1\/$var2\" | bc)\n\nCalculate for float values\n\n  printf \"%s\\n\" 'scale = 10; 196.304492\/615.348986' | bc\n\nbash-3.00$ x=$( printf \"%s\\n\" 'scale = 10; 196.304492\/615.348986' | bc)\nbash-3.00$ echo $x\n.3190132696\n\n\n\nA bash round function:\n\nround()\n{\necho $(printf %.$2f $(echo \"scale=$2;(((10^$2)*$1)+0.5)\/(10^$2)\" | bc))\n};\nUsed in your code example:\n\n#!\/bin\/bash\n# the function \"round()\" was taken from \n# the round function:\nround()\n{\necho $(printf %.$2f $(echo \"scale=$2;(((10^$2)*$1)+0.5)\/(10^$2)\" | bc))\n};\n\necho \"Insert the price you want to calculate:\"\nread float\necho \"This is the price without taxes:\"\n#echo \"scale=2; $float\/1.18\" |bc -l\necho $(round $float\/1.18 2);\nread -p \"Press any key to continue...\"\n\n\n\n\n#!\/bin\/bash\n\necho \"----- Addition ------\"\nx=10.2\ny=20.2\nz=`echo $x+$y|bc`\necho $z\necho \"------ Division -----\"\nx=3\ny=25\nz=`echo $y\/$x|bc`\necho $z\n\necho \"----- Substration -----\"\nx=20.9\ny=33.67\nz=`echo $y-$x|bc`\necho $z\n\necho \"----- Multiply -----\"\nx=2.23\ny=4.44\nz=`echo $x*$y|bc`\necho $z\n\necho \"----- Square root -----\"\nx=215\nz=`echo \"scale=4;sqrt($x)\" | bc -l`\necho $z\n\necho \"----- Powers of -----\"\nx=4.2\ny=2\nz=`echo $x^$y | bc -l`\necho $z\n\nOutput: \/floating.sh \n----- Addition ------\n30.4\n------ Division -----\n8\n----- Substration -----\n12.77\n----- Multiply -----\n9.90\n----- Square root -----\n14.6628\n----- Powers of -----\n17.64\n\n\nMath in Shell Scripts\n\n One thing that often confuses new users to the Unix \/ Linux shell, is\nhow to do (even very simple) maths. In most languages, x = x + 1 (or\neven x++) does exactly what you would expect. The Unix\/Linux shell is\ndifferent,however. It doesn\u2019t have any built-in mathematical operators\nfor variables. It can do comparisons, but maths isn\u2019t supported, not\neven simple addition.\n\n Shell script variables are by default treated as strings,not numbers,\nwhich adds some complexity to doing math in shell script. To keep with\nscript programming paradigm and allow for better math support, langua-\nges such Perl or Python would be better suited when math is desired.\nHowever, it is possible to do math with shell script.In fact, over the\nyears, multiple facilities have been added to Unix to support working\nwith numbers.\n\n You can do maths using any one of the following methods.\n\n1. Using expr command\n2  Using $(()) construct.\n3  Using let command\n4  Using bc command.\n5  Using $[] construct.\n\nexpr command:\n\n expr command performs arithmetic operations on integers. It can\nperform the four basic arithmetic operations, as well as the modulus\n(remainder function).\n\n$ expr 5 + 10\n15\n$ a=10 b=5\n$ expr $a + $b\n15\n$ expr $a \/ $b\n2\n$ expr $a * $b\nexpr: syntax error\n$ expr $a \\* $b\n50\n\n\n  The operand, be it +,-,* etc.,  must be enclosed on either side by\nwhitespace. Observe that the multiplication operand (*) has to be\nescaped to prevent the shell from interpreting it as the filename meta\ncharacter. Since expr can handle only integers, division yields only\nthe integral part.\n\n expr is often used with command substitution to assign a variable.\nFor example, you can set a variable x to the sum of two numbers:\n\n$ x=`expr $a + $b`\n$ echo $x\n15\n\n Note: As you can see, for expr, you must put spaces around the\n arguments: \"expr 123+456\" doesn\u2019t work. \"expr 123 + 456\" works.\n\n\nWith double parentheses: $(()) and (())\n\n In bash version 3.2 and later you can (and should) use $(()) and (())\nfor integer arithmetic expressions. You may have may not have spaces\naround the operators, but you must not have spaces around the equal\nsign, as with any bash variable assignment.\n\n$ c=$(($a+9))\n$ echo $c\n19\n$ c=$((a+9))             #Also correct, no need of $ sign.\n$ c=$((a + 9))           #Also correct, no restriction on spaces.\n$ c= $((a + b))          #Incorrect, space after assignment operator.\n\n\n You may also use operations within double parentheses without\nassignment.\n\n$ ((a++))\n$ echo $a\n11\n$ ((a+=1)) ; echo $a\n12\n$ ((d=a+b+9)) ; echo $d\n26\n$ ((a+=$b))                #Correct\n$ (($a+=1))                #Incorrect\n\nlet command:\n\n The let command carries out arithmetic operations on variables. In\nmany cases, it functions as a less complex version of expr command.\nAs you can see, it is also a little picky about spaces, but it wants\nthe opposite of what expr wanted. let also relaxes the normal rule of\nneeding a $ in front of variables to be read.\n\n$ let a=10            # Same as 'a=11'\n$ let a=a+5           # Equivalent to  let \"a = a + 5\"\n\n# Quotes permit the use of spaces in variable assignment. (Double\n# quotes and spaces make it more readable.)\n\n$ let a=$a + 5        # Without quotes spaces not allowed.\nbash: let: +: syntax error: operand expected (error token is \"+\")\n\n\n You need to use quotes if you want to use spaces between tokens of\nthe expression, for example\n\n$ let \"a = a + 5\";echo $a\n20\n\n The only construct that is more convenient to use with let is incre-\nment such as\n\n$ let a++ ; echo $a       #  as well as to ((i++))\n16\n\nbc: THE CALCULATOR\n\n Bash doesn't support floating point arithmetic. The obvious candidate\nfor adding floating point capabilities to bash is bc. bc is not only a\ncommand, it also a pseudo-programming language featuring arrays,funct-\nions,conditional(if) and loops(for and while). It also comes with a\nlibrary for performing scientific calculations. It can handle very,\nvery large numbers. If a computation results in a 900 digit number, bc\nwill show each and every digit. But you have to treat the variables as\nstrings.\n\n Here is what happens when we try to do floating point math with the\nshell:\n\n$ let a=12.5\nbash: let: a=12.5: syntax error: invalid arithmetic operator (error\ntoken is \".5\")\n$ ((b=1*0.5))\nbash: ((: b=1*0.5: syntax error: invalid arithmetic operator (error\ntoken is \".5\")\n\n\n    I can't explain everything about bc here, it needs another post.\nBut I will give some examples here.\n\nMost of the bellow examples follow a simple formula:\n\n$ echo '57+43' | bc\n100\n$ echo '57*43' | bc\n2451\n$ echo '6^6' | bc         # Power\n46656\n$ echo '1.5*5'|bc         # Allows floating point math.\n7.5\n\n$[] construct: \n\n$ x=85\n$ y=15\n$ echo $[x+y]\n100\n$ echo $[x\/y]\n5\n$ c=$[x*y]\n$ echo $c\n1275\n\n\n Working of above methods shell dependent. Bash shell supports all 5\nmethods. Following shell script demonstrates above methods.\n\n#!\/bin\/bash\n# SCRIPT:  basicmath.sh\n# USAGE:   basicmath.sh\n# PURPOSE: Addition, Subtraction, Division and Multiplication of\n#          two numbers.\n#                       \\\\\\\\ \/\/\/\/\n#                      \\\\  - -  \/\/\n#                          @ @\n#                  ---oOOo-( )-oOOo---\n#\n#####################################################################\n#                      Variable Declaration                         #\n#####################################################################\n\nclear                        #Clears Screen\n\nBold=\"\\033[1m\"               #Storing escape sequences in a variable.\nNormal=\"\\033[0m\"\n\necho -e \"$Bold Basic mathematics using bash script $Normal\\n\"\n\nitems=\"1. ADDITTION\n        2. SUBTRACTION\n        3. MULTIPLICATION\n        4. DIVISION\n        5. EXIT\"\n\nchoice=\n\n#####################################################################\n#                      Define Functions Here                        #\n#####################################################################\n\n# If didn't understand these functions, simply remove functions and\n# its entries from main script.\n\nexit_function()\n{\n   clear\n   exit\n}\n\n#Function enter is used to go  back to menu and clears screen\n\nenter()\n{\n   unset num1 num2\n   ans=\n   echo \"\"\n   echo -e  \"Do you want to continue(y\/n):\\c\"\n   stty -icanon min 0 time 0\n\n# When -icanon is set then one character has been received.\n# min 0 means that read should read 0 characters.\n# time 0 ensures that read is terminated the moment one character\n# is hit.\n\nwhile [ -z \"$ans\" ]\ndo\n   read ans\ndone\n\n#The while loop ensures that so long as at least one character is\n# not received read continue to get executed\n\nif [ \"$ans\" = \"y\" -o \"$ans\" = \"Y\" ]\nthen\n   stty sane          # Restoring terminal settings\n   clear\nelse\n   stty sane\n   exit_function\nfi\n}\n\n#####################################################################\n#                         Main Starts                               #\n#####################################################################\n\nwhile true\ndo\n   echo -e \"$Bold \\tPROGRAM MENU $Normal\\n\"\n   echo -e \"\\t$items \\n\"\n   echo -n \"Enter your choice : \"\n   read choice\n\n   case $choice in\n     1) clear\n        echo  \"Enter two numbers for Addition : \"\n        echo -n \"Number1: \"\n        read num1\n        echo -n \"Number2: \"\n        read num2\n        echo \"$num1 + $num2 = `expr $num1 + $num2`\"\n        enter ;;\n     2) clear\n        echo \"Enter two numbers for Subtraction : \"\n        echo -n \"Number1: \"\n        read num1\n        echo -n \"Number2: \"\n        read num2\n        echo \"$num1 - $num2 = $((num1-num2))\"\n        enter ;;\n     3) clear\n        echo \"Enter two numbers for Multiplication : \"\n        echo -n \"Number1: \"\n        read num1\n        echo -n \"Number2: \"\n        read num2\n        echo \"$num1 * $num2 = `echo \"$num1*$num2\"|bc`\"\n        enter ;;\n    4)  clear\n        echo \"Enter two numbers for Division : \"\n        echo -n \"Number1: \"\n        read num1\n        echo -n \"Number2: \"\n        read num2\n        let div=num1\/num2\n        echo \"$num1 \/ $num2 = $div\"\n        enter ;;\n    5)  exit_function  ;;\n    *)  echo \"You entered wrong option, Please enter 1,2,3,4 or 5\"\n        echo \"Press enter to continue\"\n        read\n        clear\n   esac\n\ndone \n\nOUTPUT:\n [venu@localhost ~]$ sh basicmath.sh\n\n Basic mathematics using bash script\n\n        PROGRAM MENU\n\n        1. ADDITTION\n        2. SUBTRACTION\n        3. MULTIPLICATION\n        4. DIVISION\n        5. EXIT\n\nEnter your choice : 1\n\nEnter two numbers for Addition :\nNumber1: 123\nNumber2: 456\n123 + 456 = 579\n\nDo you want to continue(y\/n):y\n\n        PROGRAM MENU\n\n        1. ADDITTION\n        2. SUBTRACTION\n        3. MULTIPLICATION\n        4. DIVISION\n        5. EXIT\n\nEnter your choice : 3\nEnter two numbers for Multiplication :\nNumber1: 12.5\nNumber2: 2\n12.5 * 2 = 25.0\n\nDo you want to continue(y\/n):n\n\n\n\nrithmetic Operators:\nThere are following arithmetic operators supported by Bourne Shell.\n\nAssume variable a holds 10 and variable b holds 20 then:\n\nShow Examples\n\nOperator\tDescription\tExample\n+\tAddition - Adds values on either side of the operator\t`expr $a + $b` will give 30\n-\tSubtraction - Subtracts right hand operand from left hand operand\t`expr $a - $b` will give -10\n*\tMultiplication - Multiplies values on either side of the operator\t`expr $a \\* $b` will give 200\n\/\tDivision - Divides left hand operand by right hand operand\t`expr $b \/ $a` will give 2\n%\tModulus - Divides left hand operand by right hand operand and returns remainder\t`expr $b % $a` will give 0\n=\tAssignment - Assign right operand in left operand\ta=$b would assign value of b into a\n==\tEquality - Compares two numbers, if both are same then returns true.\t[ $a == $b ] would return false.\n!=\tNot Equality - Compares two numbers, if both are different then returns true.\t[ $a != $b ] would return true.\nIt is very important to note here that all the conditional expressions would be put inside square braces with one spaces around them, for example [ $a == $b ] is correct where as [$a==$b] is incorrect.\n\nAll the arithmetical calculations are done using long integers.\n\nRelational Operators:\nBourne Shell supports following relational operators which are specific to numeric values. These operators would not work for string values unless their value is numeric.\n\nFor example, following operators would work to check a relation between 10 and 20 as well as in between \"10\" and \"20\" but not in between \"ten\" and \"twenty\".\n\nAssume variable a holds 10 and variable b holds 20 then:\n\nShow Examples\n\nOperator\tDescription\tExample\n-eq\tChecks if the value of two operands are equal or not, if yes then condition becomes true.\t[ $a -eq $b ] is not true.\n-ne\tChecks if the value of two operands are equal or not, if values are not equal then condition becomes true.\t[ $a -ne $b ] is true.\n-gt\tChecks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.\t[ $a -gt $b ] is not true.\n-lt\tChecks if the value of left operand is less than the value of right operand, if yes then condition becomes true.\t[ $a -lt $b ] is true.\n-ge\tChecks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.\t[ $a -ge $b ] is not true.\n-le\tChecks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.\t[ $a -le $b ] is true.\n\nIt is very important to note here that all the conditional expressions would be put inside square braces with one spaces around them, \nfor example [ $a <= $b ] is correct where as [$a <= $b] is incorrect.\n\nBoolean Operators:\nThere are following boolean operators supported by Bourne Shell.\n\nAssume variable a holds 10 and variable b holds 20 then:\n\nShow Examples\n\nOperator\tDescription\tExample\n!\tThis is logical negation. This inverts a true condition into false and vice versa.\t[ ! false ] is true.\n-o\tThis is logical OR. If one of the operands is true then condition would be true.\t[ $a -lt 20 -o $b -gt 100 ] is true.\n-a\tThis is logical AND. If both the operands are true then condition would be true otherwise it would be false.\t[ $a -lt 20 -a $b -gt 100 ] is false.\nString Operators:\nThere are following string operators supported by Bourne Shell.\n\nAssume variable a holds \"abc\" and variable b holds \"efg\" then:\n\nShow Examples\n\nOperator\tDescription\tExample\n=\tChecks if the value of two operands are equal or not, if yes then condition becomes true.\t[ $a = $b ] is not true.\n!=\tChecks if the value of two operands are equal or not, if values are not equal then condition becomes true.\t[ $a != $b ] is true.\n-z\tChecks if the given string operand size is zero. If it is zero length then it returns true.\t[ -z $a ] is not true.\n-n\tChecks if the given string operand size is non-zero. If it is non-zero length then it returns true.\t[ -z $a ] is not false.\nstr\tCheck if str is not the empty string. If it is empty then it returns false.\t[ $a ] is not false.\nFile Test Operators:\nThere are following operators to test various properties associated with a Unix file.\n\nAssume a variable file holds an existing file name \"test\" whose size is 100 bytes and has read, write and execute permission on:\n\nShow Examples\n\nOperator\tDescription\tExample\n-b file\tChecks if file is a block special file if yes then condition becomes true.\t[ -b $file ] is false.\n-c file\tChecks if file is a character special file if yes then condition becomes true.\t[ -c $file ] is false.\n-d file\tCheck if file is a directory if yes then condition becomes true.\t[ -d $file ] is not true.\n-f file\tCheck if file is an ordinary file as opposed to a directory or special file if yes then condition becomes true.\t[ -f $file ] is true.\n-g file\tChecks if file has its set group ID (SGID) bit set if yes then condition becomes true.\t[ -g $file ] is false.\n-k file\tChecks if file has its sticky bit set if yes then condition becomes true.\t[ -k $file ] is false.\n-p file\tChecks if file is a named pipe if yes then condition becomes true.\t[ -p $file ] is false.\n-t file\tChecks if file descriptor is open and associated with a terminal if yes then condition becomes true.\t[ -t $file ] is false.\n-u file\tChecks if file has its set user id (SUID) bit set if yes then condition becomes true.\t[ -u $file ] is false.\n-r file\tChecks if file is readable if yes then condition becomes true.\t[ -r $file ] is true.\n-w file\tCheck if file is writable if yes then condition becomes true.\t[ -w $file ] is true.\n-x file\tCheck if file is execute if yes then condition becomes true.\t[ -x $file ] is true.\n-s file\tCheck if file has size greater than 0 if yes then condition becomes true.\t[ -s $file ] is true.\n-e file\tCheck if file exists. Is true even if file is a directory but exists.\t[ -e $file ] is true.\n\n\n\n\n==================================================================================================================================================================================\nEscape Sequences\n\n\n\n Escape Characters\nCertain characters are significant to the shell; we have seen, for example, that the use of double quotes (\") characters affect how spaces and TAB characters are treated, for example:\n\n$ echo Hello       World\nHello World\n$ echo \"Hello       World\"\nHello     World\nSo how do we display: Hello    \"World\" ?\n\n\n$ echo \"Hello   \\\"World\\\"\"\nThe first and last \" characters wrap the whole lot into one parameter passed to echo so that the spacing between the two words is kept as is. But the code:\n\n$ echo \"Hello   \" World \"\"\nwould be interpreted as three parameters:\n\n\"Hello   \"\nWorld\n\"\"\nSo the output would be\n\nHello    World\nNote that we lose the quotes entirely. This is because the first and second quotes mark off the Hello and following spaces; the second argument is an unquoted \"World\" and the third argument is the empty string; \"\".\n\nThanks to Patrick for pointing out that this:\n\n\n$ echo \"Hello   \"World\"\"\nis actually only one parameter (no spaces between the quoted parameters), and that you can test this by replacing the echo command with (for example) ls.\nMost characters (*, ', etc) are not interpreted (ie, they are taken literally) by means of placing them in double quotes (\"\"). They are taken as is and passed on to the command being called. An example using the asterisk (*) goes:\n\n\n$ echo *\ncase.shtml escape.shtml first.shtml \nfunctions.shtml hints.shtml index.shtml \nip-primer.txt raid1+0.txt\n$ echo *txt\nip-primer.txt raid1+0.txt\n$ echo \"*\"\n*\n$ echo \"*txt\"\n*txt\nIn the first example, * is expanded to mean all files in the current directory.\nIn the second example, *txt means all files ending in txt.\nIn the third, we put the * in double quotes, and it is interpreted literally.\nIn the fourth example, the same applies, but we have appended txt to the string.\n\n\n \nHowever, \", $, `, and \\ are still interpreted by the shell, even when they're in double quotes. \nThe backslash (\\) character is used to mark these special characters so that they are not interpreted by the shell, but passed on to the command being run (for example, echo). \nSo to output the string: (Assuming that the value of $X is 5):\n\nA quote is \", backslash is \\, backtick is `.\nA few spaces are    and dollar is $. $X is 5.\nwe would have to write:\n\n$ echo \"A quote is \\\", backslash is \\\\, backtick is \\`.\"\nA quote is \", backslash is \\, backtick is `.\n$ echo \"A few spaces are    ; dollar is \\$. \\$X is ${X}.\"\nA few spaces are    ; dollar is $. $X is 5.\nWe have seen why the \" is special for preserving spacing. Dollar ($) is special because it marks a variable, so $X is replaced by the shell with the contents of the variable X. Backslash (\\) is special because it is itself used to mark other characters off; we need the following options for a complete shell:\n\n$ echo \"This is \\\\ a backslash\"\nThis is \\ a backslash\n$ echo \"This is \\\" a quote and this is \\\\ a backslash\"\nThis is \" a quote and this is \\ a backslash\n\n\n\n\nQuotes and escaping\n\nQuoting and escaping is really an important way to influence the way, Bash treats your input. There are three recognized types:\n\nper-character escaping using a backslash: \\$stuff\nweak quoting with double-quotes: \"stuff\"\nstrong quoting with single-quotes: 'stuff'\nAll three forms have the very same purpose: They give you general control over parsing, expansion and expansion's results.\n\nBeside these common basic variants, there are some more special quoting methods (like interpreting ANSI-C escapes in a string) you'll meet below.\n\n\u2757 ATTENTION \u2757 These quote characters (\", double quote and ', single quote) are a syntax element that influences parsing. It is not related to eventual quote characters that are passed as text to the commandline! The syntax-quotes are removed before the command is called! Look:\n\n### NO NO NO: this passes three strings:\n###      (1)  \"my\n###      (2)  multiword\n###      (3)  argument\"\nMYARG=\"\\\"my multiword argument\\\"\"\nsomecommand $MYARG\n\n### THIS IS NOT (!!!!) THE SAME AS ###\ncommand \"my multiword argument\"\n\n### YOU NEED ###\nMYARG=\"my multiword argument\"\ncommand \"$MYARG\"\nPer-character escaping\n\nPer-character escaping is useful in different places, also here, on expansions and substitutions. In general, a character that has a special meaning for Bash, like the dollar-sign ($) to introduce some expansion types, can be masked to not have that special meaning using the backslash:\n\necho \\$HOME is set to \\\"$HOME\\\"\n\\$HOME won't expand because it's not variable expansion syntax anymore\nThe quotes are masked with the backslash to be literal - otherwise they would be interpreted by Bash\nThe sequence \\<newline> (an unquoted backslash, followed by a <newline> character) is interpreted as line continuation. It is removed from the input stream and thus effectively ignored. Use it to beautify your code:<\/p>\n<p># escapestr_sed()<br \/>\n# read a stream from stdin and escape characters in text that could be interpreted as<br \/>\n# special characters by sed<br \/>\nescape_sed() {<br \/>\n sed \\<br \/>\n  -e &#8216;s\/\\\/\/\\\\\\\/\/g&#8217; \\<br \/>\n  -e &#8216;s\/\\&#038;\/\\\\\\&#038;\/g&#8217;<br \/>\n}<br \/>\nThe backslash can be used to mask every character that has a special meaning for bash. Exception: Inside a single-quoted string (see below).<\/p>\n<p>Weak quoting<\/p>\n<p>Inside a weak-quoted string there&#8217;s no special interpretion of:<\/p>\n<p>spaces as word-separators (on inital commandline splitting and on word splitting!)<br \/>\nsingle-quotes to introduce strong-quoting (see below)<br \/>\ncharacters for pattern matching<br \/>\npathname expansion<br \/>\nprocess substitution<br \/>\nEverything else, especially parameter expansion, is performed!<\/p>\n<p>ls -l &#8220;*&#8221;<br \/>\nWill not be expanded. ls gets the literal * as argument. It will, unless you have a file named *, spit out an error.<br \/>\necho &#8220;Your PATH is: $PATH&#8221;<br \/>\nWill work as expected. $PATH is expanded, because it&#8217;s only double- (weak-) quoted.<br \/>\nIf a backslash in double-quotes (&#8220;weak quoting&#8221;) occurs, there are 2 ways to deal with it<\/p>\n<p>if the baskslash is followed by a character that would have a special meaning even inside double-quotes, the backslash is removed and the following character looses its special meaning<br \/>\nif the backslash is followed by a character without special meaning, the backslash is not removed<br \/>\nIn particuar this means that &#8220;\\$&#8221; will become $, but &#8220;\\x&#8221; will become \\x.<\/p>\n<p>Strong quoting<\/p>\n<p>Strong quoting is very easy to explain:<\/p>\n<p>Inside a single-quoted string nothing(!!!!) is interpreted, except the single-quote that closes the quoting.<\/p>\n<p>echo &#8216;Your PATH is: $PATH&#8217;<br \/>\nThat $PATH won&#8217;t be expanded, it&#8217;s interpreted as normal ordinary text, because it&#8217;s surrounded by strong quotes.<br \/>\nIn practise that means, to produce a text like Here&#8217;s my test\u2026 as a single-quoted string, you have to leave and re-enter the single-quoting to get the character &#8220;&#8216;&#8221; as literal text:<\/p>\n<p># WRONG<br \/>\necho &#8216;Here&#8217;s my test&#8230;&#8217;<\/p>\n<p># RIGHT<br \/>\necho &#8216;Here&#8217;\\&#8221;s my test&#8230;&#8217;<\/p>\n<p># ALTERNATIVE: It&#8217;s also possible to mix-and-match quotes for readability:<br \/>\necho &#8220;Here&#8217;s my test&#8221;<br \/>\nANSI C like strings<\/p>\n<p>There&#8217;s another quoting mechanism, Bash provides: Strings that are scanned for ANSI C like escape sequences. The Syntax is<\/p>\n<p>$&#8217;string&#8217;<br \/>\nwhere the following escape sequences are decoded in string:<br \/>\nCode\tMeaning<br \/>\n\\&#8221;\tdouble-quote<br \/>\n\\&#8217;\tsingle-quote<br \/>\n\\\\\tbackslash<br \/>\n\\a\tterminal alert character (bell)<br \/>\n\\b\tbackspace<br \/>\n\\e\tescape (ASCII 033)<br \/>\n\\E\tescape (ASCII 033) \\E is non-standard<br \/>\n\\f\tform feed<br \/>\n\\n\tnewline<br \/>\n\\r\tcarriage return<br \/>\n\\t\thorizontal tab<br \/>\n\\v\tvertical tab<br \/>\n\\cx\ta control-x character, for example $&#8217;\\cZ&#8217; to print the control sequence composed by Ctrl-Z (^Z)<br \/>\n\\uXXXX\tInterprets XXXX as hexadecimal number and prints the corresponding character from the character set (4 digits) (Bash 4.2-alpha)<br \/>\n\\UXXXXXXXX\tInterprets XXXX as hexadecimal number and prints the corresponding character from the character set (8 digits) (Bash 4.2-alpha)<br \/>\n\\nnn\tthe eight-bit character whose value is the octal value nnn (one to three digits)<br \/>\n\\xHH\tthe eight-bit character whose value is the hexadecimal value HH (one or two hex digits)<\/p>\n<p>hell scripts commonly used ANSI escape codes for color output.<br \/>\nFollowing table shows Numbers representing colors in Escape Sequences.<\/p>\n<p>Color\tForeground\tBackground<br \/>\nBlack\t30\t40<br \/>\nRed\t31\t41<br \/>\nGreen\t32\t42<br \/>\nYellow\t33\t43<br \/>\nBlue\t34\t44<br \/>\nMagenta\t35\t45<br \/>\nCyan\t36\t46<br \/>\nWhite\t37\t47<\/p>\n<p>The numbers in the above table work for xterm terminal.Result may vary<br \/>\nfor other terminal emulators.<\/p>\n<p>Use the following template for writing colored text.<\/p>\n<p>echo -e &#8220;\\033[COLORm Sample text&#8221;<\/p>\n<p>The &#8220;\\033[&#8221; begins the escape sequence.You can also use &#8220;\\e[&#8221; instead<br \/>\nof &#8220;\\033[&#8220;. COLOR specifies a foreground color, according to the table<br \/>\nabove.The &#8220;m&#8221; terminates escape sequence, and text begins immediately<br \/>\nafter that.<\/p>\n<p>Note: With an echo, the -e option enables the escape sequences.You can<\/p>\n<p>also use printf instead of echo.<\/p>\n<p>printf &#8220;\\e[COLORm sample text\\n&#8221;<\/p>\n<p>To print Green text<\/p>\n<p>echo -e &#8220;\\033[32m Hello World&#8221;<br \/>\n             or<br \/>\nprintf &#8220;\\e[32m Hello World&#8221;<\/p>\n<p>The problem with above statement is that the blue color that starts<br \/>\nwith the 32 color code is never switched back to the regular color, so<br \/>\nany text you type after the prompt and even prompt also is still in the<br \/>\nGreen color.<\/p>\n<p>To return to the plain, normal mode, we have yet another sequence.<\/p>\n<p>echo -e &#8220;\\033[0m&#8221;<\/p>\n<p>Now you won&#8217;t see anything new on the screen, as this echo statement<br \/>\nwas not passed any string to display. But it has done its job, which<br \/>\nwas to restore the normal viewing mode. Whatever yor type now will be<br \/>\navoid of any fancy effects.<\/p>\n<p>Escape sequence also allow you to control the manner in which<br \/>\ncharacters are displayed on the screen.<\/p>\n<p>The following table summarizes numbers representing text attributes<br \/>\nin Escape Sequences.<\/p>\n<p>ANSI CODE\tMeaning<br \/>\n0\tNormal Characters<br \/>\n1\tBold Characters<br \/>\n4\tUnderlined Characters<br \/>\n5\tBlinking Characters<br \/>\n7\tReverse video Characters<\/p>\n<p>Note: Blink attribute doesn&#8217;t work in any terminal emulator, but it<\/p>\n<p>will work on the console.<\/p>\n<p>Combining all these Escape Sequences, you can get more fancy effect.<br \/>\nUse the following template for writing colored text on a colored<br \/>\nbackground.<\/p>\n<p>echo -e &#8220;\\033[COLOR1;COLOR2m sample text\\033[0m&#8221;<\/p>\n<p>The semicolon separated numbers &#8220;COLOR1&#8221; and &#8220;COLOR2&#8243; specify a<br \/>\nforeground and a background color.The order of the numbers does not<br \/>\nmatter, since the foreground and background numbers fall in non-<br \/>\noverlapping ranges.&#8221;m&#8221; terminates the escape sequence, and the text<br \/>\nbegins immediately after that.Although setting the colors separately<br \/>\nalso work (i.e. \\033[44m\\033[32m).<\/p>\n<p>There are some differences between colors when combining colors with<br \/>\nbold text attribute.<\/p>\n<p>The following table summarises these differences.<\/p>\n<p>Bold off\tcolor\tBold on\tcolor<br \/>\n0;30\tBalck\t1;30\tDark Gray<br \/>\n0;31\tRed\t1;31\tDark Red<br \/>\n0;32\tGreen\t1;32\tDark Green<br \/>\n0;33\tBrown\t1;33\tYellow<br \/>\n0;34\tBlue\t1;34\tDark Blue<br \/>\n0;35\tMagenta\t1;35\tDark Magenta<br \/>\n0;36\tCyan\t1;30\tDark Cyan<br \/>\n0;37\tLight Gray\t1;30\tWhite<\/p>\n<p>The following shell script prints all the colors and codes on the<br \/>\nscreen.<\/p>\n<p>#!\/bin\/bash<\/p>\n<p># This script echoes colors and codes<\/p>\n<p>echo -e &#8220;\\n\\033[4;31mLight Colors\\033[0m  \\t\\t\\033[1;4;31mDark Colors\\033[0m&#8221;<\/p>\n<p>echo -e &#8220;\\e[0;30;47m Black    \\e[0m 0;30m \\t\\e[1;30;40m Dark Gray  \\e[0m 1;30m&#8221;<\/p>\n<p>echo -e &#8220;\\e[0;31;47m Red      \\e[0m 0;31m \\t\\e[1;31;40m Dark Red   \\e[0m 1;31m&#8221;<\/p>\n<p>echo -e &#8220;\\e[0;32;47m Green    \\e[0m 0;32m \\t\\e[1;32;40m Dark Green \\e[0m 1;32m&#8221;<\/p>\n<p>echo -e &#8220;\\e[0;33;47m Brown    \\e[0m 0;33m \\t\\e[1;33;40m Yellow     \\e[0m 1;33m&#8221;<\/p>\n<p>echo -e &#8220;\\e[0;34;47m Blue     \\e[0m 0;34m \\t\\e[1;34;40m Dark Blue  \\e[0m 1;34m&#8221;<\/p>\n<p>echo -e &#8220;\\e[0;35;47m Magenta  \\e[0m 0;35m \\t\\e[1;35;40m DarkMagenta\\e[0m 1;35m&#8221;<\/p>\n<p>echo -e &#8220;\\e[0;36;47m Cyan     \\e[0m 0;36m \\t\\e[1;36;40m Dark Cyan  \\e[0m 1;36m&#8221;<\/p>\n<p>echo -e &#8220;\\e[0;37;47m LightGray\\e[0m 0;37m \\t\\e[1;37;40m White      \\e[0m 1;37m&#8221;<\/p>\n<p>OUTPUT:<\/p>\n<p>Some examples:<\/p>\n<p>Block background and white text<\/p>\n<p>echo -e &#8220;\\033[40;37m Hello World\\033[0m&#8221;<\/p>\n<p>Reverse video text attribute option interchanges fg and bg colors.<br \/>\nBellow statement prints block on white<\/p>\n<p>echo -e &#8220;\\033[40;37;7m Hello World\\033[0m&#8221;<\/p>\n<p>echo -e &#8220;\\033[33;44m Yellow text on blue background\\033[0m&#8221;<br \/>\necho -e &#8220;\\033[1;33;44m Bold yellow text on blue background\\033[0m&#8221;<br \/>\necho -e &#8220;\\033[1;4;33;44mBold yellow underlined text on blue background\\033[0m&#8221;<\/p>\n<p>The &#8220;tput&#8221; command:<\/p>\n<p>         Other than echo there is a command called tput using which we<br \/>\ncan control the way the output is displayed on the screen.But it is<br \/>\nless flexible than ANSI escape sequences.<\/p>\n<p>#!\/bin\/bash<br \/>\necho &#8220;Hey world, \\what&#8217;s up?&#8221;<\/p>\n<p>Users who have been using Linux for awhile often learn that creating a basic script is a good way to run multiple, often-repeated commands. Adding a little color to scripts can additionally provide nice feedback. This can be done in a fairly straight-forward way by using the tput command.<\/p>\n<p>A common way of doing this is to define the colors that tput can produce by putting them at the beginning of the bash script:<\/p>\n<p>#!\/bin\/bash<br \/>\n# scriptname &#8211; description of script<\/p>\n<p># Text color variables<br \/>\ntxtund=$(tput sgr 0 1)          # Underline<br \/>\ntxtbld=$(tput bold)             # Bold<br \/>\nbldred=${txtbld}$(tput setaf 1) #  red<br \/>\nbldblu=${txtbld}$(tput setaf 4) #  blue<br \/>\nbldwht=${txtbld}$(tput setaf 7) #  white<br \/>\ntxtrst=$(tput sgr0)             # Reset<br \/>\ninfo=${bldwht}*${txtrst}        # Feedback<br \/>\npass=${bldblu}*${txtrst}<br \/>\nwarn=${bldred}*${txtrst}<br \/>\nques=${bldblu}?${txtrst}<br \/>\nWhen writing new scripts using templates with these variables already defined can quicken the creation process and help keep scripts organized (my Bash Templates).<\/p>\n<p>If just needing to use tput colors for specific instances this script can display the tput definitions and their corresponding possibilities:<\/p>\n<p>#!\/bin\/bash<br \/>\n# tputcolors<\/p>\n<p>echo<br \/>\necho -e &#8220;$(tput bold) reg  bld  und   tput-command-colors$(tput sgr0)&#8221;<\/p>\n<p>for i in $(seq 1 7); do<br \/>\n  echo &#8221; $(tput setaf $i)Text$(tput sgr0) $(tput bold)$(tput setaf $i)Text$(tput sgr0) $(tput sgr 0 1)$(tput setaf $i)Text$(tput sgr0)  \\$(tput setaf $i)&#8221;<br \/>\ndone<\/p>\n<p>echo &#8216; Bold            $(tput bold)&#8217;<br \/>\necho &#8216; Underline       $(tput sgr 0 1)&#8217;<br \/>\necho &#8216; Reset           $(tput sgr0)&#8217;<br \/>\necho<\/p>\n<p>tput Command<\/p>\n<p>The tput command is used to set terminal features. With tput you can set:<\/p>\n<p>Move the cursor around the screen.<br \/>\nGet information about terminal.<br \/>\nSet colors (background and foreground).<br \/>\nSet bold mode.<br \/>\nSet reverse mode and much more.<br \/>\nHere is a sample code:<\/p>\n<p>#!\/bin\/bash<\/p>\n<p># clear the screen<br \/>\ntput clear<\/p>\n<p># Move cursor to screen location X,Y (top left is 0,0)<br \/>\ntput cup 3 15<\/p>\n<p># Set a foreground colour using ANSI escape<br \/>\ntput setaf 3<br \/>\necho &#8220;XYX Corp LTD.&#8221;<br \/>\ntput sgr0<\/p>\n<p>tput cup 5 17<br \/>\n# Set reverse video mode<br \/>\ntput rev<br \/>\necho &#8220;M A I N &#8211; M E N U&#8221;<br \/>\ntput sgr0<\/p>\n<p>tput cup 7 15<br \/>\necho &#8220;1. User Management&#8221;<\/p>\n<p>tput cup 8 15<br \/>\necho &#8220;2. Service Management&#8221;<\/p>\n<p>tput cup 9 15<br \/>\necho &#8220;3. Process Management&#8221;<\/p>\n<p>tput cup 10 15<br \/>\necho &#8220;4. Backup&#8221;<\/p>\n<p># Set bold mode<br \/>\ntput bold<br \/>\ntput cup 12 15<br \/>\nread -p &#8220;Enter your choice [1-4] &#8221; choice<\/p>\n<p>tput clear<br \/>\ntput sgr0<br \/>\ntput rc<\/p>\n<p>===================================if-then=====================================================================================<br \/>\nif-then&#8217; Statement in Action<\/p>\n<p>check the exit status  wither command executed successfully or not <\/p>\n<p>[root@cluster1 shell]# mkdir test<br \/>\n[root@cluster1 shell]# echo $?<br \/>\n0<br \/>\n[root@cluster1 shell]# mkdir test<br \/>\nmkdir: cannot create directory `test&#8217;: File exists<br \/>\n[root@cluster1 shell]# echo $?<br \/>\n1<br \/>\n[root@cluster1 shell]#<\/p>\n<p>What Are Conditions?<\/p>\n<p>Conditions in the realm of computing work similarly. We can test whether a string matches another string, whether it doesn\u2019t match another string, or even if it exists at all.<br \/>\nSimilarly, we can test numerical arguments to see if one is great than, less than, or equal to another. <\/p>\n<p>To get something to happen after the conditions of the test are met, we use \u201cif-then\u201d statements. Their format is pretty simple.<\/p>\n<p>if CONDITION<br \/>\nthen<br \/>\ncommand1<br \/>\ncommand2<br \/>\n\u2026<br \/>\ncommandn<br \/>\nfi<\/p>\n<p>if test $1 -gt $2<br \/>\nthen<br \/>\necho \u201c$1 is greater than $2?<br \/>\nfi<\/p>\n<p> if&#8230;fi statement is the fundamental control statement that allows Shell to make decisions and execute statements conditionally.<\/p>\n<p>Syntax:<br \/>\nif [ expression ]<br \/>\nthen<br \/>\n   Statement(s) to be executed if expression is true<br \/>\nfi<br \/>\nHere Shell expression is evaluated. If the resulting value is true, given statement(s) are executed. If expression is false then no statement would be not executed. Most of the times you will use comparison operators while making decisions.<\/p>\n<p>Give you attention on the spaces between braces and expression. This space is mandatory otherwise you would get syntax error.<\/p>\n<p>If expression is a shell command then it would be assumed true if it return 0 after its execution. If it is a boolean expression then it would be true if it returns true.<\/p>\n<p>Example:<br \/>\n#!\/bin\/sh<\/p>\n<p>a=10<br \/>\nb=20<\/p>\n<p>if [ $a == $b ]<br \/>\nthen<br \/>\n   echo &#8220;a is equal to b&#8221;<br \/>\nfi<\/p>\n<p>if [ $a != $b ]<br \/>\nthen<br \/>\n   echo &#8220;a is not equal to b&#8221;<br \/>\nfi<br \/>\nThis will produce following result:<\/p>\n<p>a is not equal to b<\/p>\n<p>Here are some other numerical operators you may want to try out:<\/p>\n<p>-eq: equal to<br \/>\n-ne: not equal to<br \/>\n-lt: less than<br \/>\n-le: less than or equal to<br \/>\n-gt: greater than<br \/>\n-ge: greater than or equal to<\/p>\n<p>Shell scripts use fairly standard syntax for if statements. The conditional statement is executed using either the test command or the [ command. In its most basic form an if statement is:<\/p>\n<p>#!\/bin\/bash<\/p>\n<p>if [ &#8220;$#&#8221; -gt 0 ]<br \/>\nthen<br \/>\n    echo &#8220;There&#8217;s Beans&#8221;<br \/>\nfi<\/p>\n<p>if [ &#8220;$1&#8221; = &#8220;cool&#8221; ]<br \/>\nthen<br \/>\n    echo &#8220;Cool Beans&#8221;<br \/>\nfi<br \/>\n(Notice that the fi is simply if spelled backwards). To add an else, we just use standard syntax.<\/p>\n<p>#!\/bin\/bash<\/p>\n<p>if [ &#8220;$1&#8221; = &#8220;cool&#8221; ]<br \/>\nthen<br \/>\n    echo &#8220;Cool Beans&#8221;<br \/>\nelse<br \/>\n    echo &#8220;Not Cool Beans&#8221;<br \/>\nfi<br \/>\nAdding an else-if statement structure is used with the elif command.<\/p>\n<p>#!\/bin\/bash<\/p>\n<p>if [ &#8220;$1&#8221; = &#8220;cool&#8221; ]<br \/>\nthen<br \/>\n    echo &#8220;Cool Beans&#8221;<br \/>\nelif [ &#8220;$1&#8221; = &#8220;neat&#8221; ]<br \/>\nthen<br \/>\n    echo &#8220;Neato cool&#8221;<br \/>\nelse<br \/>\n    echo &#8220;Not Cool Beans&#8221;<br \/>\nfi<br \/>\nAn if statement does not require two parameters. You can use single flags as well. The following code tests to see if the first parameter is a file or not.<\/p>\n<p>#!\/bin\/bash<\/p>\n<p>if [ -f &#8220;$1&#8221; ]<br \/>\nthen<br \/>\n    echo &#8220;$1 is a file&#8221;<br \/>\nelse<br \/>\n    echo &#8220;$1 is not a file&#8221;<br \/>\nfi<br \/>\nThere are many different ways that an conditional statement can be used. These are summarized here:<\/p>\n<p>String Comparison\tDescription<br \/>\nStr1 = Str2\tReturns true if the strings are equal<br \/>\nStr1 != Str2\tReturns true if the strings are not equal<br \/>\n-n Str1\tReturns true if the string is not null<br \/>\n-z Str1\tReturns true if the string is null<\/p>\n<p>Numeric Comparison\tDescription<br \/>\nexpr1 -eq expr2\tReturns true if the expressions are equal<br \/>\nexpr1 -ne expr2\tReturns true if the expressions are not equal<br \/>\nexpr1 -gt expr2\tReturns true if expr1 is greater than expr2<br \/>\nexpr1 -ge expr2\tReturns true if expr1 is greater than or equal to expr2<br \/>\nexpr1 -lt expr2\tReturns true if expr1 is less than expr2<br \/>\nexpr1 -le expr2\tReturns true if expr1 is less than or equal to expr2<br \/>\n! expr1\tNegates the result of the expression<\/p>\n<p>File Conditionals\tDescription<br \/>\n-d file\tTrue if the file is a directory<br \/>\n-e file\tTrue if the file exists (note that this is not particularly portable, thus -f is generally used)<br \/>\n-f file\tTrue if the provided string is a file<br \/>\n-g file\tTrue if the group id is set on a file<br \/>\n-r file\tTrue if the file is readable<br \/>\n-s file\tTrue if the file has a non-zero size<br \/>\n-u\tTrue if the user id is set on a file<br \/>\n-w\tTrue if the file is writable<br \/>\n-x\tTrue if the file is an executable<\/p>\n<p>File attributes comparisons<\/p>\n<p>-a file<br \/>\nTrue if file exists.<\/p>\n<p>Example<br \/>\n[ -a \/etc\/resolv.conf ] &#038;&#038; echo &#8220;File found&#8221; || echo &#8220;Not found&#8221;<br \/>\n-b file<br \/>\nTrue if file exists and is a block special file.<\/p>\n<p>Example<br \/>\n[ -b \/dev\/zero ] &#038;&#038; echo &#8220;block special file found&#8221; || echo &#8220;block special file not found&#8221;<br \/>\nOR<\/p>\n<p>[ -b \/dev\/sda ] &#038;&#038; echo &#8220;block special file found&#8221; || echo &#8220;block special file not found&#8221;<br \/>\n-c file<br \/>\nTrue if file exists and is a character special file.<\/p>\n<p>Example<br \/>\n[ -c \/dev\/tty0  ] &#038;&#038; echo &#8220;Character special file found.&#8221; || echo &#8220;Character special file not found.&#8221;<br \/>\n-d dir<br \/>\nTrue if file exists and is a directory.<\/p>\n<p>Example<br \/>\n#!\/bin\/bash<br \/>\nDEST=&#8221;\/backup&#8221;<br \/>\nSRC=&#8221;\/home&#8221;<\/p>\n<p># Make sure backup dir exits<br \/>\n[ ! -d &#8220;$DEST&#8221; ] &#038;&#038; mkdir -p &#8220;$DEST&#8221;<\/p>\n<p># If source directory does not exits, die&#8230;<br \/>\n[ ! -d &#8220;$SRC&#8221; ] &#038;&#038; { echo &#8220;$SRC directory not found. Cannot make backup to $DEST&#8221;; exit 1; }<\/p>\n<p># Okay, dump backup using tar<br \/>\necho &#8220;Backup directory $DEST&#8230;&#8221;<br \/>\necho &#8220;Source directory $SRC&#8230;&#8221;<br \/>\n\/bin\/tar zcf &#8220;$DEST\/backup.tar.gz&#8221; &#8220;$SRC&#8221; 2>\/dev\/null<\/p>\n<p># Find out if our backup job failed or not and notify on screen<br \/>\n[ $? -eq 0 ] &#038;&#038; echo &#8220;Backup done!&#8221; || echo &#8220;Backup failed&#8221;<br \/>\n-e file<br \/>\nTrue if file exists.<\/p>\n<p>Example<br \/>\n[ -e \/tmp\/test.txt ] &#038;&#038; echo &#8220;File found&#8221; || echo &#8220;File not found&#8221;<br \/>\n-f file<br \/>\nTrue if file exists and is a regular file.<\/p>\n<p>Example<br \/>\n[ ! -f \/path\/to\/file ] &#038;&#038; echo &#8220;File not found!&#8221;<br \/>\nA sample shell script that compare various file attributes and create webalizer (application that generates web pages of analysis, from access and usage log) stats configuration file to given Internet domain name.<\/p>\n<p>#!\/bin\/bash<br \/>\n# Purpose: A Shell Script To Create Webalizer Stats Configration File<br \/>\n# Written by: Vivek Gite<br \/>\n# &#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;<br \/>\n# Set vars<\/p>\n<p># Apache vroot for each domain<br \/>\nHTTPDROOT=&#8221;\/home\/httpd&#8221;<\/p>\n<p># Path to GeoIP DB<br \/>\nGEOIPDBPATH=&#8221;\/usr\/local\/share\/GeoIP\/GeoIP.dat&#8221;<\/p>\n<p># Get the Internet domain such as cyberciti.biz<br \/>\necho &#8220;*** A Shell Script To Create Webalizer Stats Configration File ***&#8221;<br \/>\nread -p &#8220;Enter a domain name : &#8221; DOMAIN<\/p>\n<p># Make sure we got the Input else die with an error on screen<br \/>\n[ -z $DOMAIN ] &#038;&#038; { echo &#8220;Please enter a domain name. Try again!&#8221;; exit 1; }<\/p>\n<p># Alright, set some variable based upon $DOMAIN<br \/>\nOUT=&#8221;$HTTPDROOT\/$DOMAIN\/stats\/webalizer.conf&#8221;<br \/>\nCONFROOT=&#8221;$HTTPDROOT\/$DOMAIN\/stats&#8221;<br \/>\nLOGFILE=&#8221;$HTTPDROOT\/$DOMAIN\/logs\/access.log&#8221;<\/p>\n<p># Die if configuration file exits&#8230;<br \/>\n[ -f $OUT ] &#038;&#038; { echo &#8220;Webalizer configuration file &#8216;$OUT&#8217; exits for domain $DOMAIN.&#8221;; exit 2; }<\/p>\n<p># Make sure configuration directory exists<br \/>\n[ ! -d $CONFROOT ] &#038;&#038; mkdir -p $CONFROOT <\/p>\n<p># Write a log file <\/p>\n<p>>$OUT<br \/>\necho &#8220;LogFile $LOGFILE&#8221;  >> $OUT<br \/>\necho &#8220;LogType clf&#8221;  >> $OUT<br \/>\necho &#8220;OutputDir     $CONFROOT\/out&#8221;  >> $OUT<br \/>\necho &#8220;HistoryName     $CONFROOT\/webalizer.hist&#8221;  >> $OUT<br \/>\necho &#8220;Incremental     yes&#8221;  >> $OUT<br \/>\necho &#8220;IncrementalName $CONFROOT\/webalizer.current&#8221;  >> $OUT<br \/>\necho &#8220;HostName       $DOMAIN&#8221;  >> $OUT<br \/>\necho &#8220;Quiet           yes&#8221;  >> $OUT<br \/>\necho &#8220;FoldSeqErr      yes&#8221;  >> $OUT<br \/>\necho &#8220;AllSearchStr    yes&#8221;  >> $OUT<br \/>\necho &#8220;HideSite        $DOMAIN&#8221;  >> $OUT<br \/>\necho &#8220;HideSite        localhost&#8221;  >> $OUT<br \/>\necho &#8220;HideReferrer    $DOMAIN&#8221;  >> $OUT<br \/>\necho &#8220;HideURL         *.gif&#8221;  >> $OUT<br \/>\necho &#8220;HideURL         *.GIF&#8221;  >> $OUT<br \/>\necho &#8220;HideURL         *.jpg&#8221;  >> $OUT<br \/>\necho &#8220;HideURL         *.JPG&#8221;  >> $OUT<br \/>\necho &#8220;HideURL         *.png&#8221;  >> $OUT<br \/>\necho &#8220;HideURL         *.PNG&#8221;  >> $OUT<br \/>\necho &#8220;HideURL         *.ra&#8221;  >> $OUT<br \/>\necho &#8220;GroupReferrer   yahoo.com\/      Yahoo!&#8221;  >> $OUT<br \/>\necho &#8220;GroupReferrer   excite.com\/     Excite&#8221;  >> $OUT<br \/>\necho &#8220;GroupReferrer   infoseek.com\/   InfoSeek&#8221;  >> $OUT<br \/>\necho &#8220;GroupReferrer   webcrawler.com\/ WebCrawler&#8221;  >> $OUT<br \/>\necho &#8220;SearchEngine    .yahoo.         p=&#8221;  >> $OUT<br \/>\necho &#8220;SearchEngine    altavista.com   q=&#8221;  >> $OUT<br \/>\necho &#8220;SearchEngine    .google.        q=&#8221;  >> $OUT<br \/>\necho &#8220;SearchEngine    eureka.com      q=&#8221;  >> $OUT<br \/>\necho &#8220;SearchEngine    lycos.com       query=&#8221;  >> $OUT<br \/>\necho &#8220;SearchEngine    hotbot.com      MT=&#8221;  >> $OUT<br \/>\necho &#8220;SearchEngine    msn.com         MT=&#8221;  >> $OUT<br \/>\necho &#8220;SearchEngine    infoseek.com    qt=&#8221;  >> $OUT<br \/>\necho &#8220;SearchEngine    webcrawler      searchText=&#8221;  >> $OUT<br \/>\necho &#8220;SearchEngine    excite          search=&#8221;  >> $OUT<br \/>\necho &#8220;SearchEngine    netscape.com    search=&#8221;  >> $OUT<br \/>\necho &#8220;SearchEngine    mamma.com       query=&#8221;  >> $OUT<br \/>\necho &#8220;SearchEngine    alltheweb.com   query=&#8221;  >> $OUT<br \/>\necho &#8220;SearchEngine    northernlight.com  qr=&#8221;  >> $OUT<br \/>\necho &#8220;CountryFlags yes&#8221;  >> $OUT<br \/>\necho &#8220;GeoIP yes&#8221;  >> $OUT<br \/>\necho &#8220;GeoIPDatabase $GEOIPDBPATH&#8221;  >> $OUT<br \/>\necho &#8220;GraphMonths 72&#8221;  >> $OUT<br \/>\necho &#8220;IndexMonths 120&#8221;  >> $OUT<br \/>\necho &#8220;GraphMonths 72&#8221;  >> $OUT<br \/>\necho &#8220;TopReferrers 20&#8221;  >> $OUT<br \/>\necho &#8220;TopSites 20&#8221;  >> $OUT<br \/>\necho &#8220;TopURLs 50&#8221;  >> $OUT<br \/>\necho &#8220;TopKURLs 50&#8221;  >> $OUT<\/p>\n<p>echo &#8220;Weblizer config wrote to $OUT&#8221;<br \/>\n-g file<br \/>\nTrue if file exists and is set-group-id.<\/p>\n<p>-h file<br \/>\nTrue if file exists and is a symbolic link.<\/p>\n<p>-k file<br \/>\nTrue if file exists and its \u2018\u2018sticky\u2019\u2019 bit is set.<\/p>\n<p>-p file<br \/>\nTrue if file exists and is a named pipe (FIFO).<\/p>\n<p>-r file<br \/>\nTrue if file exists and is readable.<\/p>\n<p>-s file<br \/>\nTrue if file exists and has a size greater than zero.<\/p>\n<p>-t fd<br \/>\nTrue if file descriptor fd is open and refers to a terminal.<\/p>\n<p>-u file<br \/>\nTrue if file exists and its set-user-id bit is set.<\/p>\n<p>-w file<br \/>\nTrue if file exists and is writable.<\/p>\n<p>-x file<br \/>\nTrue if file exists and is executable.<\/p>\n<p>-O file<br \/>\nTrue if file exists and is owned by the effective user id.<\/p>\n<p>-G file<br \/>\nTrue if file exists and is owned by the effective group id.<\/p>\n<p>-L file<br \/>\nTrue if file exists and is a symbolic link.<\/p>\n<p>-S file<br \/>\nTrue if file exists and is a socket.<\/p>\n<p>-N file<br \/>\nTrue if file exists and has been modified since it was last read.<\/p>\n<p>In its most basic form an if statement is:<br \/>\n#!\/bin\/bash if [ &#8220;$1&#8221; -eq &#8220;abc&#8221; ] then echo &#8220;in if block&#8221; fi<br \/>\n(Notice that the fi is simply if spelled backwards).<\/p>\n<p>To add an else, we just use standard syntax.<\/p>\n<p>#!\/bin\/bash if [ &#8220;$1&#8221; -eq &#8220;abc&#8221; ] then echo &#8220;in if block&#8221; else echo &#8220;in else block&#8221; fi<br \/>\nAdding an else-if statement structure is used with the elif command.<\/p>\n<p>#!\/bin\/bash if [ &#8220;$1&#8221; -eq &#8220;abc&#8221; ] then echo &#8220;in if block&#8221; elif [ &#8220;$1&#8221; -eq &#8220;xyz&#8221; ] echo &#8220;in else if block&#8221; else echo &#8220;in else block&#8221; fi<br \/>\nAn if statement does not require two parameters.<\/p>\n<p>You can use single flags as well. The following code tests to see if the first parameter is a file or not.<\/p>\n<p>#!\/bin\/bash if [ -f &#8220;$1&#8221; ] then echo &#8220;$1 is a file&#8221; else echo &#8220;$1 is not a file&#8221; fi<\/p>\n<p>#!\/bin\/bash<br \/>\n#if then statement<br \/>\necho &#8220;Enter source and target files names.&#8221;<br \/>\nread   source target<br \/>\nif mv $source $target<br \/>\nthen<br \/>\necho &#8220;Your file has been successully renamed..&#8221;<br \/>\nfi <\/p>\n<p>Enter source and target files names.<br \/>\ntest test1<br \/>\nYour file has been successully renamed..<br \/>\n[root@cluster1 shell]# ls -ltr<\/p>\n<p>if&#8230;else&#8230;fi statement is the next form of control statement that allows Shell to execute statements in more controlled way and making decision between two choices.<\/p>\n<p>Syntax:<br \/>\nif [ expression ]<br \/>\nthen<br \/>\n   Statement(s) to be executed if expression is true<br \/>\nelse<br \/>\n   Statement(s) to be executed if expression is not true<br \/>\nfi<br \/>\nHere Shell expression is evaluated. If the resulting value is true, given statement(s) are executed. If expression is false then no statement would be not executed.<\/p>\n<p> then<br \/>\n                       command executed successfully<br \/>\n                       execute all commands up to else statement<br \/>\n                       or to fi if there is no else statement<\/p>\n<p>           else<br \/>\n                       command failed so<br \/>\n                       execute all commands up to fi<br \/>\n           fi<br \/>\nOR<\/p>\n<p>           if test var -eq val<br \/>\n           then<br \/>\n                       command executed successfully<br \/>\n                       execute all commands up to else statement<br \/>\n                       or to fi if there is no else statement<\/p>\n<p>           else<br \/>\n                       if command failed then<br \/>\n                       execute all commands up to fi<br \/>\n           fi<br \/>\nOR<\/p>\n<p>           if [ condition ]<br \/>\n           then<br \/>\n                       if given condition true<br \/>\n                       execute all commands up to else statement<br \/>\n                       or to fi if there is no else statement<\/p>\n<p>           else<br \/>\n                       if given condition false<br \/>\n                       execute all commands up to fi<br \/>\n           fi<\/p>\n<p>if [ condition ]<br \/>\nthen<br \/>\n    < code block ><br \/>\nfi<br \/>\nFor example \u2013 If we need to check if input value is equal to 10 or not. If value is equal to 10, then it will print \u201cValue of i is 10?, but if not nothing will be printed.<\/p>\n<p>#!\/bin\/bash<br \/>\nread -p &#8220;Enter value of i :&#8221; i<\/p>\n<p>if [ $i -eq 10 ]<br \/>\nthen<br \/>\n    echo &#8220;Value of i is 10&#8221;<br \/>\nfi<br \/>\n2. Bash if else Statement<\/p>\n<p>if else statements are useful where we have a two programs for execution, and need to execute only one based on results of if condition.<\/p>\n<p>if [ condition ]<br \/>\nthen<br \/>\n    < code block ><br \/>\nelse<br \/>\n    < code block ><br \/>\nfi<br \/>\nFor example \u2013 If input taken value is 10 then it will print \u201cValue of i is 10?, if not program will execute else block statement and print \u201cValue of i is not equal to 10?.<\/p>\n<p>#!\/bin\/bash<br \/>\nread -p &#8220;Enter value of i :&#8221; i<\/p>\n<p>if [ $i -eq 10 ]<br \/>\nthen<br \/>\n    echo &#8220;Value of i is 10&#8221;<br \/>\nelse<br \/>\n    echo &#8220;Value of i is not equal to 10&#8221;<br \/>\nfi<br \/>\n3. Bash if elif Statement<\/p>\n<p>if elif and else statements are useful where we have more than two programs for execution, and need to execute only one based on results of if and elif condition.<\/p>\n<p>if [ condition ]<br \/>\nthen<br \/>\n    < code block ><br \/>\nelif [ condition ]<br \/>\nthen<br \/>\n    < code block ><br \/>\nelse<br \/>\n    < code block ><br \/>\nfi<br \/>\nFor example \u2013 Below example will check input value if equal to 5, if its true then program will print \u201cValue of i is 5? otherwise program will go to elif statement where one more conditional will be checked and based of these results elif or elase block code will be executed.<\/p>\n<p>#!\/bin\/bash<br \/>\nread -p &#8220;Enter value of i :&#8221; i<\/p>\n<p>if [ $i -eq 5 ]<br \/>\nthen<br \/>\n    echo &#8220;Value of i is 5&#8221;<br \/>\nelif [ $i -eq 10 ]<br \/>\nthen<br \/>\n    echo &#8220;Value of i is 10&#8221;<br \/>\nelse<br \/>\n    echo &#8220;Value of i is not equal to 5 or 10&#8221;<br \/>\nfi<br \/>\n4. Bash elif Ladder Statements<\/p>\n<p>This is something similar to above one where we are adding multiple elif statements together. elif (else if) ladder are useful where we have multiple programs for execution and need to execute only one based on results of if and elif condition.<\/p>\n<p>if [ condition ]<br \/>\nthen<br \/>\n    < code block ><\/p>\n<p>elif [ condition ]<br \/>\nthen<br \/>\n    < code block ><\/p>\n<p>elif [ condition ]<br \/>\nthen<br \/>\n    < code block ><\/p>\n<p>elif [ condition ]<br \/>\nthen<br \/>\n    < code block ><\/p>\n<p>else<br \/>\n    < code block ><br \/>\nfi<br \/>\nFor example \u2013<\/p>\n<p>#!\/bin\/bash<br \/>\nread -p &#8220;Enter value of i :&#8221; i<\/p>\n<p>if [ $i -eq 5 ]<br \/>\nthen<br \/>\n    echo &#8220;Value of i is 5&#8221;<br \/>\nelif [ $i -eq 10 ]<br \/>\nthen<br \/>\n    echo &#8220;Value of i is 10&#8221;<br \/>\nelif [ $i -eq 20 ]<br \/>\nthen<br \/>\n    echo &#8220;Value of i is 20&#8221;<br \/>\nelif [ $i -eq 30 ]<br \/>\nthen<br \/>\n    echo &#8220;Value of i is 30&#8221;<br \/>\nelse<br \/>\n    echo &#8220;Value of i is not equal to 5,10,20 or 30&#8221;<br \/>\nfi<br \/>\n5. Bash nested if Statements<\/p>\n<p>Nested if are useful in the situation where one condition will be checked based on results of outer condition.<\/p>\n<p>if [ condition ]<br \/>\nthen<br \/>\n    if [ condition ]<br \/>\n    then<br \/>\n        < code block ><br \/>\n    else<br \/>\n        < code block ><br \/>\n    fi<br \/>\nelse<br \/>\n    if [ condition ]<br \/>\n    then<br \/>\n        < code block ><br \/>\n    fi<br \/>\nfi<br \/>\nFor example below small shell program is for finding the greatest value between 3 values taken input by user. This program will work with numeric values only. If two values are similar it will print only one value.<\/p>\n<p>#!\/bin\/bash<\/p>\n<p>read -p &#8220;Enter value of i :&#8221; i<br \/>\nread -p &#8220;Enter value of j :&#8221; j<br \/>\nread -p &#8220;Enter value of k :&#8221; k<\/p>\n<p>if [ $i -gt $j ]<br \/>\nthen<br \/>\n    if [ $i -gt $k ]<br \/>\n    then<br \/>\n        echo &#8220;i is greatest&#8221;<br \/>\n    else<br \/>\n        echo &#8220;k is greatest&#8221;<br \/>\n    fi<br \/>\nelse<br \/>\n    if [ $j -gt $k ]<br \/>\n    then<br \/>\n        echo &#8220;j is greatest&#8221;<br \/>\n    else<br \/>\n\t    echo &#8220;k is greatest&#8221;<br \/>\n    fi<br \/>\nfi<\/p>\n<p>Nested ifs<\/p>\n<p>if condition<br \/>\n\tthen<br \/>\n\t\tif condition<br \/>\n\t\tthen<br \/>\n\t\t\t&#8230;..<br \/>\n\t\t\t..<br \/>\n\t\t\tdo this<br \/>\n\t\telse<br \/>\n\t\t\t&#8230;.<br \/>\n\t\t\t..<br \/>\n\t\t\tdo this<br \/>\n\t\tfi<br \/>\n\telse<br \/>\n\t\t&#8230;<br \/>\n\t\t&#8230;..<br \/>\n\t\tdo this<br \/>\n\tfi<\/p>\n<p>Number Testing Script<br \/>\nCreate a shell script called testnum.sh:<br \/>\n#!\/bin\/bash<br \/>\nread -p &#8220;Enter number : &#8221; n<br \/>\nif test $n -ge 0<br \/>\nthen<br \/>\n\techo &#8220;$n is positive number.&#8221;<br \/>\nelse<br \/>\n\techo &#8220;$n number is negative number.&#8221;<br \/>\nfi<\/p>\n<p>!\/bin\/bash<br \/>\n#if then statement<br \/>\necho &#8220;Enter source and target files names.&#8221;<br \/>\nread  source target<br \/>\nif mv $source $target<br \/>\nthen<br \/>\necho &#8220;Your file has been successully renamed..&#8221;<br \/>\nelse<br \/>\necho &#8220;Your file is not been moved&#8230;&#8221;<br \/>\nfi<\/p>\n<p>#!\/bin\/bash<\/p>\n<p>read -p &#8220;Enter first Number:&#8221; n1<br \/>\nread -p &#8220;Enter second Number:&#8221; n2<br \/>\nread -p &#8220;Enter third Number:&#8221; n3<br \/>\nread -p &#8220;Enter fourth Number:&#8221; n4<\/p>\n<p>if((n1>n2)) ; then<br \/>\nif((n1>n3)); then<br \/>\n if((n1>n4)); then<br \/>\necho &#8220;$n1 is a Greatest Number&#8221;<br \/>\nelse<br \/>\necho &#8220;$n4 is a Greatest Number&#8221;<br \/>\nfi<br \/>\n elif((n3>n4)); then<br \/>\necho &#8220;$n3 is a Greatest Number&#8221;<br \/>\nelse<br \/>\necho &#8220;$n4 is a Greatest Number&#8221;<br \/>\nfi<br \/>\nelif((n2>n3)); then<br \/>\nif((n2>n4)); then<br \/>\necho &#8220;$n2 is a Greatest Number&#8221;<br \/>\nelse<br \/>\necho &#8220;$n4 is a Greatest Number&#8221;<br \/>\n fi<br \/>\nelif((n3>n4)); then<br \/>\necho &#8220;$n3 is a Greatest Number&#8221;<br \/>\nelse<br \/>\necho &#8220;$n4 is a Greatest Number&#8221;<br \/>\nfi<\/p>\n<p>========================================Exit status of a command  Parameters Set by the Shell==================================================================<\/p>\n<p>exit status of a command  Parameters Set by the Shell<\/p>\n<p>Bash shell set several special parameters. For example $? (see return values section) holds the return value of the executed command.<\/p>\n<p>All command line parameters or arguments can be accessed via $1, $2, $3,&#8230;, $9.<br \/>\n$* holds all command line parameters or arguments.<br \/>\n$# holds the number of positional parameters.<br \/>\n$- holds flags supplied to the shell.<br \/>\n$? holds the return value set by the previously executed command.<br \/>\n$$ holds the process number of the shell (current shell).<br \/>\n$! hold the process number of the last background command.<br \/>\n$@ holds all command line parameters or arguments.<br \/>\nUse echo command to display special shell parameters:<\/p>\n<p>echo $#<br \/>\nYou can store them to a shell variables as follows:<\/p>\n<p>status=$?<br \/>\n[ $status -eq 0 ] &#038;&#038; echo &#8220;Lighttpd &#8230; [Ok]&#8221; || echo &#8220;Lighttpd &#8230; [Failed]&#8221;<br \/>\nAssignment to special parameter is not allowed:<br \/>\n# okay<br \/>\nstatus=$?<br \/>\n# noop not allowed<br \/>\n$?=-1<\/p>\n<p>Exit Status<br \/>\nEvery Linux command executed by the shell script or user, has an exit status.<br \/>\nThe exit status is an integer number.<br \/>\nThe Linux man pages stats the exit statuses of each command.<br \/>\n0 exit status means the command was successful without any errors.<br \/>\nA non-zero (1-255 values) exit status means command was failure.<br \/>\nYou can use special shell variable called ? to get the exit status of the previously executed command. To print ? variable use the echo command:<br \/>\necho $?<br \/>\ndate  # run date command<br \/>\necho $? # print exit status<br \/>\nfoobar123 # not a valid command<br \/>\necho $? # print exit status<br \/>\nHow Do I See Exit Status Of The Command?<br \/>\nType the following command:<br \/>\ndate<br \/>\nTo view exist status of date command, enter:<\/p>\n<p>echo $?<br \/>\nSample Output:<\/p>\n<p>0<br \/>\nTry non-existence command<\/p>\n<p>date1<br \/>\necho $?<br \/>\nls \/eeteec<br \/>\necho $?<br \/>\nSample Output:<\/p>\n<p>2<br \/>\nAccording to ls man page &#8211; exit status is 0 if OK, 1 if minor problems, 2 if serious trouble.<\/p>\n<p>How Do I Store Exit Status Of The Command In a Shell Variable?<br \/>\nAssign $? to a shell variable:<\/p>\n<p>ls -l \/tmp<br \/>\nstatus=$?<br \/>\necho &#8220;ls command exit stats &#8211; $status&#8221;<br \/>\nExit Status Shell Script Example<br \/>\nA simple shell script to locate username (finduser.sh)<\/p>\n<p>#!\/bin\/bash<br \/>\n# set var<br \/>\nPASSWD_FILE=\/etc\/passwd<\/p>\n<p># get user name<br \/>\nread -p &#8220;Enter a user name : &#8221; username<\/p>\n<p># try to locate username in in \/etc\/passwd<br \/>\ngrep &#8220;^$username&#8221; $PASSWD_FILE > \/dev\/null<\/p>\n<p># store exit status of grep<br \/>\n# if found grep will return 0 exit stauts<br \/>\n# if not found, grep will return a nonzero exit stauts<br \/>\nstatus=$?<\/p>\n<p>if test $status -eq 0<br \/>\nthen<br \/>\n\techo &#8220;User &#8216;$username&#8217; found in $PASSWD_FILE file.&#8221;<br \/>\nelse<br \/>\n\techo &#8220;User &#8216;$username&#8217; not found in $PASSWD_FILE file.&#8221;<br \/>\nfi<br \/>\nSave and close the file. Run it as follows:<\/p>\n<p>chmod +x finduser.sh<br \/>\n.\/finduser.sh<br \/>\nSample Outputs:<\/p>\n<p>Enter a user name : vivek<br \/>\nUser &#8216;vivek&#8217; found in \/etc\/passwd file.<br \/>\nRun it again:<\/p>\n<p>chmod +x finduser.sh<br \/>\n.\/finduser.sh<br \/>\nSample Outputs:<\/p>\n<p>Enter a user name : tommy<br \/>\nUser &#8216;tommy&#8217; not found in \/etc\/passwd file.<br \/>\nYou can combine the grep and if command in a single statement as follows:<\/p>\n<p>if grep &#8220;^$username:&#8221; \/etc\/passwd >\/dev\/null<br \/>\nthen<br \/>\n\techo &#8220;User &#8216;$username&#8217; found in $PASSWD_FILE file.&#8221;<br \/>\nelse<br \/>\n\techo &#8220;User &#8216;$username&#8217; not found in $PASSWD_FILE file.&#8221;<br \/>\nfi<\/p>\n<p>#!\/bin\/bash<br \/>\necho &#8220;Enter a number between  10 and 20 &#8221;<br \/>\nread num<br \/>\nif [ $num -lt 10 ]<br \/>\nthen<br \/>\necho &#8220;That was under the limit you entered&#8221;<br \/>\nelif [ $num -gt 20 ]<br \/>\nthen<br \/>\necho &#8220;That over  the limit you entered&#8221;<br \/>\nelse<br \/>\n       echo &#8220;Now your are over the limit&#8221;<br \/>\nfi <\/p>\n<p>#!\/bin\/bash<br \/>\necho &#8220;Enter file name :\\c&#8221;<br \/>\nread fname<br \/>\nif [ -f $fname ]<br \/>\nthen<br \/>\n    if [ -w $fname ]<br \/>\n\t    then<br \/>\n\t\t  echo &#8220;Type matter to append. To quit press ctrl+d &#8221;<br \/>\n           cat >> $fname<br \/>\n         else<br \/>\n          echo &#8220;You do not have permission to write. &#8221;<br \/>\n    fi<br \/>\nfi \t\t  <\/p>\n<p>#!\/bin\/sh<\/p>\n<p># Prompt for a user name&#8230;<br \/>\necho &#8220;Please enter your name:&#8221;<br \/>\nread USERNAME<\/p>\n<p># Check for the file.<br \/>\nif [ -s ${USERNAME}_DAT ]; then<br \/>\n        # Read the age from the file.<br \/>\n        AGE=`cat ${USERNAME}_DAT`<br \/>\n        echo &#8220;You are $AGE years old!&#8221;<br \/>\nelse<br \/>\n        # Ask the user for his\/her age<br \/>\n        echo &#8220;How old are you?&#8221;<br \/>\n        read AGE<\/p>\n<p>\tif [ &#8220;$AGE&#8221; -le 2 ]; then<br \/>\n\t\techo &#8220;You are too young!&#8221;<br \/>\n\telse<br \/>\n\t\tif [ &#8220;$AGE&#8221; -ge 100 ]; then<br \/>\n\t\t\techo &#8220;You are too old!&#8221;<br \/>\n\t\telse<br \/>\n        \t\t# Write the age to a new file.<br \/>\n        \t\techo $AGE > ${USERNAME}_DAT<br \/>\n        \tfi<br \/>\n        fi<br \/>\nfi<\/p>\n<p>The syntax is as follows:<\/p>\n<p> exit N<br \/>\nThe exit statement is used to exit from the shell script with a status of N.<br \/>\nUse the exit statement to indicate successful or unsuccessful shell script termination.<br \/>\nThe value of N can be used by other commands or shell scripts to take their own action.<br \/>\nIf N is omitted, the exit status is that of the last command executed.<br \/>\nUse the exit statement to terminate shell script upon an error.<br \/>\nIf N is set to 0 means normal shell exit. Create a shell script called exitcmd.sh:<br \/>\n#!\/bin\/bash<br \/>\necho &#8220;This is a test.&#8221;<br \/>\n# Terminate our shell script with success message<br \/>\nexit 0<br \/>\nSave and close the file. Run it as follows:<\/p>\n<p>chmod +x exitcmd.sh<br \/>\n.\/exitcmd.sh<br \/>\nSample outputs:<\/p>\n<p>This is a test.<br \/>\nTo see exit status of the script, enter (see the exit status of a command for more information about special shell variable $?) :<\/p>\n<p>echo $?<br \/>\nShell script example<br \/>\nAny non zero value indicates unsuccessful shell script termination.<br \/>\nCreate a shell script called datatapebackup.sh:<br \/>\n#!\/bin\/bash<br \/>\nBAK=\/data2<br \/>\nTAPE=\/dev\/st0<br \/>\necho &#8220;Trying to backup ${BAK} directory to tape device ${TAPE} ..&#8221;<\/p>\n<p># See if $BAK exits or not else die<br \/>\n# Set unsuccessful shell script termination with exit status # 1<br \/>\n[ ! -d $BAK ] &#038;&#038; { echo &#8220;Source backup directory $BAK not found.&#8221;; exit 1; }<\/p>\n<p># See if $TAPE device exits or not else die<br \/>\n# Set unsuccessful shell script termination with exit status # 2<br \/>\n[ ! -b $TAPE ] &#038;&#038; { echo &#8220;Backup tape drive $TAPE not found or configured.&#8221;; exit 2; }<\/p>\n<p># Okay back it up<br \/>\ntar cvf $TAPE $BAK 2> \/tmp\/error.log<\/p>\n<p>if [ $? -ne 0 ]<br \/>\nthen<br \/>\n   # die with unsuccessful shell script termination exit status # 3<br \/>\n   echo &#8220;An error occurred while making a tape backup, see \/tmp\/error.log file&#8221;.<br \/>\n   exit 3<br \/>\nfi<\/p>\n<p># Terminate our shell script with success message i.e. backup done!<br \/>\nexit 0<br \/>\nSave and close the file. Run it as follows:<\/p>\n<p>chmod +x datatapebackup.sh<br \/>\n.\/datatapebackup.sh<br \/>\necho $?<\/p>\n<p>=============================================================================================<br \/>\nString Comparison Operators in Shell Script<\/p>\n<p>OPERATOR DESCRIPTION<br \/>\nstr1 = str2 True if str1 and str2 are identical<br \/>\nstr1 != str2 True if str1 and str2 are not identical<br \/>\n-n str1 True if str1 is not null (size is greater than zero)<br \/>\n-z str1 True if str1 is null <\/p>\n<p>$ cat > strtest.sh <\/p>\n<p>#!\/bin\/bash<br \/>\na=&#8217;mohan&#8217; b=&#8217;mohan&#8217; c=&#8217;server&#8217;<br \/>\n#null string<br \/>\nd=&#8217; &#8216;<br \/>\nif [ $a = $b ] ; then<br \/>\necho &#8220;a and b are identical&#8221;<br \/>\nfi<br \/>\nif [ $a != $c ] ; then<br \/>\necho &#8220;a and c are not identical&#8221; fi<br \/>\nif [ -z $d ] ; then<br \/>\necho &#8220;d is a null string&#8221;<br \/>\nfi <\/p>\n<p>Sourcesystem=&#8221;ABC&#8221;<\/p>\n<p>if [ &#8220;$Sourcesystem&#8221; = &#8220;XYZ&#8221; ]; then<br \/>\n    echo &#8220;Sourcesystem Matched&#8221;<br \/>\nelse<br \/>\n    echo &#8220;Sourcesystem is NOT Matched $Sourcesystem&#8221;<br \/>\nfi;<\/p>\n<p>if [ &#8216;XYZ&#8217; == &#8216;ABC&#8217; ]; then   # Double equal to will work in Linux but not on HPUX boxes it should be if [ &#8216;XYZ&#8217; = &#8216;ABC&#8217; ] which will work on both<br \/>\n  echo &#8220;Match&#8221;<br \/>\nelse<br \/>\n  echo &#8220;No Match&#8221;<br \/>\nfi<\/p>\n<p>if [ &#8220;$var&#8221; == &#8220;&#8221; ] then<br \/>\necho variable is null<br \/>\nfi<\/p>\n<p>To determine if the value of a variable is not empty:<\/p>\n<p>if [ &#8220;$var&#8221; != &#8220;&#8221; ] then<br \/>\necho variable is not null<br \/>\nfi<\/p>\n<p>To compare the contents of a variable to a fixed string:<\/p>\n<p>if [ &#8220;$var&#8221; == &#8220;value&#8221; ] then<br \/>\necho is the same<br \/>\nfi<\/p>\n<p>To determine if variable\u2019s contents are not equal to a fixed string:<\/p>\n<p>if [ &#8220;$var&#8221; != &#8220;value&#8221; ] then<br \/>\necho not the same<br \/>\nfi<\/p>\n<p>Empty string in Bash<\/p>\n<p>In Bash you quite often need to check to see if a variable has been set or has a value other than an empty string. This can be done using the -n or -z string comparison operators.<\/p>\n<p>The -n operator checks whether the string is not null. Effectively, this will return true for every case except where the string contains no characters. ie:<\/p>\n<p>VAR=&#8221;hello&#8221;<br \/>\nif [ -n &#8220;$VAR&#8221; ]; then<br \/>\n    echo &#8220;VAR is not empty&#8221;<br \/>\nfi<\/p>\n<p>Similarly, the -z operator checks whether the string is null. ie:<\/p>\n<p>VAR=&#8221;&#8221;<br \/>\nif [ -z &#8220;$VAR&#8221; ]; then<br \/>\n    echo &#8220;VAR is empty&#8221;<br \/>\nfi<\/p>\n<p>The following program shows the comparison of two strings in shell script<\/p>\n<p>#!\/bin\/sh<br \/>\nstr1=&#8221;happy&#8221;<br \/>\nstr2=&#8221;happy&#8221;<br \/>\n[ $str1 = $str2 ]<br \/>\necho $?<\/p>\n<p>Case Insensitive comparision of strings in Shell script<\/p>\n<p>str1=&#8221;MATCH&#8221;<br \/>\nstr2=&#8221;match&#8221;<br \/>\nshopt -s nocasematch<br \/>\ncase &#8220;$str1&#8221; in<br \/>\n $str2 ) echo &#8220;match&#8221;;;<br \/>\n *) echo &#8220;no match&#8221;;;<br \/>\nesac<\/p>\n<p>var1=match<br \/>\nvar2=MATCH<br \/>\nif echo $var1 | grep -i &#8220;^${var2}$&#8221; > \/dev\/null ; then<br \/>\n  echo &#8220;MATCH&#8221;<br \/>\nfi<\/p>\n<p>I want to compare 2 strings with ignore case in bash shell.<\/p>\n<p>Suppose, if [ &#8220;test&#8221; = &#8220;TEst&#8221; ] &#8230; should be true and enter into if loop.<\/p>\n<p>Solution:<\/p>\n<p>Please try this:<\/p>\n<p>if [ `echo &#8220;TeSt&#8221; | tr -s &#8216;[:upper:]&#8217; &#8216;[:lower:]` = `echo &#8220;Test&#8221; | tr -s &#8216;[:upper:]&#8217; &#8216;[:lower:]` ]<br \/>\nthen<br \/>\necho &#8220;true&#8221;<br \/>\nelse<br \/>\necho &#8220;false&#8221;<br \/>\nfi<\/p>\n<p>or<\/p>\n<p>Try similar, it still worked.<\/p>\n<p>input=TESt<br \/>\ninput=`echo $input | tr &#8216;[A-Z]&#8217; &#8216;[a-z]&#8217;`<\/p>\n<p>if [[ &#8220;$input&#8221; =~ &#8220;test&#8221; ]]; then<br \/>\necho &#8220;equal&#8221;<br \/>\nelse<br \/>\necho &#8220;not equal&#8221;<br \/>\nfi<\/p>\n<p>#!\/bin\/bash<br \/>\nstr1=&#8221;Hey You!&#8221;<br \/>\nstr2=&#8221;What&#8217;s up?&#8221;<br \/>\nstr3=&#8221;&#8221;<\/p>\n<p>[ &#8220;$str1&#8221; = &#8220;$str2&#8221; ]<br \/>\necho $?<\/p>\n<p>[ &#8220;$str1&#8221; != &#8220;$str2&#8221; ]<\/p>\n<p>echo $?<\/p>\n<p>[ -n &#8220;$str1&#8221; ]<\/p>\n<p>echo $?<\/p>\n<p>[ -z &#8220;$str3&#8221; ]<\/p>\n<p>echo $?<\/p>\n<p>=================================================================================================<br \/>\nThe &#8216;AND&#8217; Logical Operator<\/p>\n<p>Logical and (&#038;&#038;) is boolean operator. It can execute commands or shell functions based on the exit status of another command.<\/p>\n<p>command1 &#038;&#038; command2<br \/>\nOR<\/p>\n<p>First_command &#038;&#038; Second_command<\/p>\n<p>Boolean AND:<\/p>\n<p>&#038;&#038; or -a used to do boolean AND operations in bash\/shell scripts.<\/p>\n<p>To validate boolean AND condition there are two ways:<\/p>\n<p>if [ $condition1 ] &#038;&#038; [ $condition2 ]<br \/>\nYou can also validate as<\/p>\n<p>if [ $condition1 -a $condition2 ]<\/p>\n<p>Type the following at a shell prompt:<\/p>\n<p>rm \/tmp\/filename &#038;&#038; echo &#8220;File deleted.&#8221;<br \/>\nLookup a username in \/etc\/passwd file<br \/>\ngrep &#8220;^vivek&#8221; \/etc\/passwd &#038;&#038; echo &#8220;Vivek found in \/etc\/passwd&#8221;<br \/>\nExit if a directory \/tmp\/foo does not exist<br \/>\ntest ! -d \/tmp\/foo &#038;&#038; { read -p &#8220;Directory \/tmp\/foo not found. Hit [Enter] to exit&#8230;&#8221; enter; exit 1; }<\/p>\n<p>#!\/bin\/bash<br \/>\necho &#8220;Enter a number between 50 and 100&#8221;<br \/>\nread num<br \/>\nif [ $num -le 100 -a $num -ge 50 ]<br \/>\nthen<br \/>\n    echo &#8220;You are within limits.&#8221;<br \/>\nelse<br \/>\n   echo &#8220;Your are out of limits.&#8221;<br \/>\nfi<\/p>\n<p>You can test multiple expressions at once by using the || (or) operator or the &#038;&#038; (and) operator. This can save you from writing extra code to nest if statements. The above code has a nested if statement where it checks if the age is greater than or equal to 100. This could be changed as well by using elif (else if). The structure of elif is the same as the structure of if, we will use it in an example below. In this example, we will check for certain age ranges. If you are less than 20 or greater than 50, you are out of the age range. If you are between 20 and 30 you are in your 20&#8217;s and so on.<br \/>\n#!\/bin\/sh<\/p>\n<p># Prompt for a user name&#8230;<br \/>\necho &#8220;Please enter your age:&#8221;<br \/>\nread AGE<\/p>\n<p>if [ &#8220;$AGE&#8221; -lt 20 ] || [ &#8220;$AGE&#8221; -ge 50 ]; then<br \/>\n\techo &#8220;Sorry, you are out of the age range.&#8221;<br \/>\nelif [ &#8220;$AGE&#8221; -ge 20 ] &#038;&#038; [ &#8220;$AGE&#8221; -lt 30 ]; then<br \/>\n\techo &#8220;You are in your 20s&#8221;<br \/>\nelif [ &#8220;$AGE&#8221; -ge 30 ] &#038;&#038; [ &#8220;$AGE&#8221; -lt 40 ]; then<br \/>\n\techo &#8220;You are in your 30s&#8221;<br \/>\nelif [ &#8220;$AGE&#8221; -ge 40 ] &#038;&#038; [ &#8220;$AGE&#8221; -lt 50 ]; then<br \/>\n\techo &#8220;You are in your 40s&#8221;<br \/>\nfi<\/p>\n<p>Count The Number of Characters in User&#8217;s Input in Your Script<\/p>\n<p>#!\/bin\/bash<br \/>\necho &#8220;Enter a charcter &#8221;<br \/>\nread var<br \/>\nif [ &#8216;echo $var  | wc -c `  -eq 2 ]<br \/>\nthen<br \/>\n     echo &#8220;You entered a character. &#8221;<br \/>\nelse<br \/>\n      echo &#8220;Invalid Input.&#8221;<br \/>\nfi <\/p>\n<p>===========================================================================================<br \/>\nLogical OR<\/p>\n<p>Logical OR (||) is boolean operator. It can execute commands or shell functions based on the exit status of another command.<\/p>\n<p>Syntax<br \/>\ncommand1 || command2<br \/>\nOR<\/p>\n<p>First_command || Second_command<br \/>\ncommand2 is executed if, and only if, command1 returns a non-zero exit status. In other words, run command1 successfully or run command2.<\/p>\n<p>Boolean OR:<\/p>\n<p>|| or -o used to do boolean OR operations in bash\/shell scripts.<\/p>\n<p>To validate boolean OR there are 2 ways:<\/p>\n<p>if [ $condition1 ] || [ $condition2 ]<br \/>\nYou can also validate boolean OR as<\/p>\n<p>if [ $condition1 -o $condition2 ]<\/p>\n<p>Example<br \/>\ncat \/etc\/shadow 2>\/dev\/null || echo &#8220;Failed to open file&#8221;<br \/>\nThe cat command will try to display \/etc\/shadow file and it (the cat command) sets the exit stats to non-zero value if it failed to open \/etc\/shadow file. Therefore, &#8216;Failed to open file&#8217; will be displayed cat command failed to open the file.<\/p>\n<p>Find username else display an error<br \/>\ngrep &#8220;^vivek&#8221; \/etc\/passwd || echo &#8220;User vivek not found in \/etc\/passwd&#8221;<br \/>\nHow Do I Combine Both Logical Operators?<br \/>\nTry it as follows:<\/p>\n<p>cat \/etc\/shadow 2>\/dev\/null &#038;&#038; echo &#8220;File successfully opened.&#8221; || echo &#8220;Failed to open file.&#8221;<br \/>\nMake sure only root can run this script:<\/p>\n<p>test $(id -u) -eq 0  &#038;&#038; echo &#8220;You are root&#8221; || echo &#8220;You are NOT root&#8221;<br \/>\nOR<\/p>\n<p>test $(id -u) -eq 0  &#038;&#038; echo &#8220;Root user can run this script.&#8221; || echo &#8220;Use sudo or su to become a root user.&#8221;<\/p>\n<p>=============================================================================================================================================================<\/p>\n<p>Logical Not !<\/p>\n<p>Logical not (!) is boolean operator, which is used to test whether expression is true or not. For example, if file not exists, then display an error on screen.<\/p>\n<p>Syntax<br \/>\nThe test command syntax is as follows:<\/p>\n<p>! expression<br \/>\nOR<\/p>\n<p>[ ! expression ]<br \/>\nOR<\/p>\n<p>if test ! condition<br \/>\nthen<br \/>\n     command1<br \/>\n     command2<br \/>\nfi<br \/>\nif [ ! condition ]<br \/>\nthen<br \/>\n     command1<br \/>\n     command2<br \/>\nfi<br \/>\nWhere,<\/p>\n<p>True if expression is false.<br \/>\nExamples<br \/>\nTry the following example:<\/p>\n<p>test ! -f \/etc\/resolv.conf &#038;&#038; echo &#8220;File \/etc\/resolv.conf not found.&#8221;<br \/>\nOR<\/p>\n<p>test ! -f \/etc\/resolv.conf &#038;&#038; echo &#8220;File \/etc\/resolv.conf not found.&#8221; || echo &#8220;File \/etc\/resolv.conf found.&#8221;<br \/>\nCreate a directory \/backup, if doesn&#8217;t exits:<\/p>\n<p>[ ! -d \/backup ] &#038;&#038; mkdir \/backup<br \/>\nDie (exit) if $HOME\/.config file not found:<\/p>\n<p>[ ! -f $HOME\/.config ] &#038;&#038; { echo &#8220;Error: $HOME\/.config file not found.&#8221;; exit 1; }<br \/>\nDie (exit) if directory \/usr\/bin not found<\/p>\n<p>[ ! -d \/usr\/bin ] &#038;&#038; exit<\/p>\n<p>================================================================================================================<\/p>\n<p>count<\/p>\n<p>#!\/bin\/bash<br \/>\nBEGIN=1 # Start counting here<br \/>\nEND=10 # Stop counting here<\/p>\n<p>END=`expr $END + 1`<\/p>\n<p>while [ $END -ne $BEGIN ]; do # While END is not equal to BEGIN do &#8230;<br \/>\n  echo This is iteration $BEGIN<br \/>\n  BEGIN=`expr $BEGIN + 1` # Increasing the value of BEGIN by one<br \/>\ndone<\/p>\n<p>========================================================================================================<br \/>\nConditional expression<\/p>\n<p>The test command is used to check file types and compare values. You can also use [ as test command. It is used for:<\/p>\n<p>File attributes comparisons<br \/>\nPerform string comparisons.<br \/>\nArithmetic comparisons.<br \/>\nSyntax<br \/>\n[ condition ]<br \/>\nOR<\/p>\n<p>[ ! condition ]<br \/>\nOR<\/p>\n<p>[ condition ] &#038;&#038; true-command<br \/>\nOR<\/p>\n<p>[ condition ] || false-command<br \/>\nOR<\/p>\n<p>[ condition ] &#038;&#038; true-command || false-command<br \/>\nExamples<br \/>\n[ 5 == 5 ] &#038;&#038; echo &#8220;Yes&#8221; || echo &#8220;No&#8221;<br \/>\n[ 5 == 15 ] &#038;&#038; echo &#8220;Yes&#8221; || echo &#8220;No&#8221;<br \/>\n[ 5 != 10 ] &#038;&#038; echo &#8220;Yes&#8221; || echo &#8220;No&#8221;<br \/>\n[ -f \/etc\/resolv.conf ] &#038;&#038; echo &#8220;File \/etc\/resolv.conf found.&#8221; || echo &#8220;File \/etc\/resolv.conf not found.&#8221;<br \/>\n[ -f \/etc\/resolv1.conf ] &#038;&#038; echo &#8220;File \/etc\/resolv.conf found.&#8221; || echo &#8220;File \/etc\/resolv.conf not found.&#8221;<\/p>\n<p>====================================================================================================<br \/>\nThe &#8216;case&#8217; Statement<\/p>\n<p>he case statement is good alternative to multilevel if-then-else-fi statement. It enable you to match several values against one variable. It is easier to read and write.<\/p>\n<p>Syntax<br \/>\nThe syntax is as follows:<\/p>\n<p>          case  $variable-name  in<br \/>\n                pattern1)<br \/>\n     \t\t    command1<br \/>\n                    &#8230;<br \/>\n                    &#8230;.<br \/>\n                    commandN<br \/>\n                    ;;<br \/>\n                pattern2)<br \/>\n     \t\t    command1<br \/>\n                    &#8230;<br \/>\n                    &#8230;.<br \/>\n                    commandN<br \/>\n                    ;;<br \/>\n                patternN)<br \/>\n     \t\t    command1<br \/>\n                    &#8230;<br \/>\n                    &#8230;.<br \/>\n                    commandN<br \/>\n                    ;;<br \/>\n                *)<br \/>\n          esac<br \/>\nOR<\/p>\n<p>          case  $variable-name  in<br \/>\n                pattern1|pattern2|pattern3)<br \/>\n     \t\t    command1<br \/>\n                    &#8230;<br \/>\n                    &#8230;.<br \/>\n                    commandN<br \/>\n                    ;;<br \/>\n                pattern4|pattern5|pattern6)<br \/>\n     \t\t    command1<br \/>\n                    &#8230;<br \/>\n                    &#8230;.<br \/>\n                    commandN<br \/>\n                    ;;<br \/>\n                pattern7|pattern8|patternN)<br \/>\n     \t\t    command1<br \/>\n                    &#8230;<br \/>\n                    &#8230;.<br \/>\n                    commandN<br \/>\n                    ;;<br \/>\n                *)<br \/>\n          esac<br \/>\nThe case statement allows you to easily check pattern (conditions) and then process a command-line if that condition evaluates to true.<br \/>\nIn other words the $variable-name is compared against the patterns until a match is found.<br \/>\n*) acts as default and it is executed if no match is found.<br \/>\nThe pattern can include wildcards.<br \/>\nYou must include ;; at the end of each commandN. The shell executes all the statements up to the two semicolons that are next to each other.<br \/>\nThe esac is always required to indicate end of case statement.<br \/>\nExample<br \/>\nCreate a shell script called rental.sh:<\/p>\n<p>#!\/bin\/bash<\/p>\n<p># if no command line arg given<br \/>\n# set rental to Unknown<br \/>\nif [ -z $1 ]<br \/>\nthen<br \/>\n  rental=&#8221;*** Unknown vehicle ***&#8221;<br \/>\nelif [ -n $1 ]<br \/>\nthen<br \/>\n# otherwise make first arg as a rental<br \/>\n  rental=$1<br \/>\nfi<\/p>\n<p># use case statement to make decision for rental<br \/>\ncase $rental in<br \/>\n   &#8220;car&#8221;) echo &#8220;For $rental rental is Rs.20 per k\/m.&#8221;;;<br \/>\n   &#8220;van&#8221;) echo &#8220;For $rental rental is Rs.10 per k\/m.&#8221;;;<br \/>\n   &#8220;jeep&#8221;) echo &#8220;For $rental rental is Rs.5 per k\/m.&#8221;;;<br \/>\n   &#8220;bicycle&#8221;) echo &#8220;For $rental rental 20 paisa per k\/m.&#8221;;;<br \/>\n   &#8220;enfield&#8221;) echo &#8220;For $rental rental Rs.3  per k\/m.&#8221;;;<br \/>\n   &#8220;thunderbird&#8221;) echo &#8220;For $rental rental Rs.5 per k\/m.&#8221;;;<br \/>\n   *) echo &#8220;Sorry, I can not get a $rental rental  for you!&#8221;;;<br \/>\nesac<br \/>\nSave and close the file. Run it as follows:<\/p>\n<p>chmod +x rental.sh<br \/>\n.\/rental.sh<br \/>\n.\/rental.sh jeep<br \/>\n.\/rental.sh enfield<br \/>\n.\/rental.sh bike<br \/>\nSample outputs:<\/p>\n<p>Sorry, I can not get a *** Unknown vehicle *** rental  for you!<br \/>\nFor jeep rental is Rs.5 per k\/m.<br \/>\nFor enfield rental Rs.3  per k\/m.<br \/>\nSorry, I can not get a bike rental  for you!<br \/>\nThe case statement first checks $rental against each option for a match. If it matches &#8220;car&#8221;, the echo command will display rental for car. If it matches &#8220;van&#8221;, the echo command will display rental for van and so on. If it matches nothing i.e. * (default option), an appropriate warning message is printed.<\/p>\n<p>Using Multiple Patterns<br \/>\n#!\/bin\/bash<br \/>\nNOW=$(date +&#8221;%a&#8221;)<br \/>\ncase $NOW in<br \/>\n\tMon)<br \/>\n\t\techo &#8220;Full backup&#8221;;;<br \/>\n\tTue|Wed|Thu|Fri)<br \/>\n\t\techo &#8220;Partial backup&#8221;;;<br \/>\n\tSat|Sun)<br \/>\n\t\techo &#8220;No backup&#8221;;;<br \/>\n\t*) ;;<br \/>\nesac<br \/>\nThe following shell script demonstrate the concept of command line parameters processing using the case statement (casecmdargs.sh):<\/p>\n<p>#!\/bin\/bash<br \/>\nOPT=$1   # option<br \/>\nFILE=$2  # filename<\/p>\n<p># test -e and -E command line args matching<br \/>\ncase $OPT in<br \/>\n  -e|-E)<br \/>\n  \techo &#8220;Editing $2 file&#8230;&#8221;<br \/>\n        # make sure filename is passed else an error displayed<br \/>\n  \t[ -z $FILE ] &#038;&#038; { echo &#8220;File name missing&#8221;; exit 1; } || vi $FILE<br \/>\n  \t;;<br \/>\n  -c|-C)<br \/>\n  \techo &#8220;Displaying $2 file&#8230;&#8221;<br \/>\n  \t[ -z $FILE ] &#038;&#038; { echo &#8220;File name missing&#8221;; exit 1; } || cat $FILE<br \/>\n  \t;;<br \/>\n  -d|-D)<br \/>\n  \techo &#8220;Today is $(date)&#8221;<br \/>\n  \t;;<br \/>\n   *)<br \/>\n    echo &#8220;Bad argument!&#8221;<br \/>\n    echo &#8220;Usage: $0 -ecd filename&#8221;<br \/>\n    echo &#8221;\t-e file : Edit file.&#8221;<br \/>\n    echo &#8221;\t-c file : Display file.&#8221;<br \/>\n    echo &#8221;\t-d      : Display current date and time.&#8221;<br \/>\n    ;;<br \/>\nesac<br \/>\nRun it as follows:<\/p>\n<p>chmod +x casecmdargs.sh<br \/>\n.\/casecmdargs.sh<br \/>\n.\/casecmdargs.sh -e \/tmp\/file<br \/>\n.\/casecmdargs.sh -E \/tmp\/file<br \/>\n.\/casecmdargs.sh -e<br \/>\n.\/casecmdargs.sh -D<br \/>\nCreating a backup script<br \/>\nCreate a backup script called allinonebackup.sh:<\/p>\n<p>#!\/bin\/bash<br \/>\n# A shell script to backup mysql, webserver and files to tape<br \/>\nopt=$1<br \/>\ncase $opt in<br \/>\n        sql)<br \/>\n                echo &#8220;Running mysql backup using mysqldump tool&#8230;&#8221;<br \/>\n                ;;<br \/>\n        sync)<br \/>\n                echo &#8220;Running backup using rsync tool&#8230;&#8221;<br \/>\n                ;;<br \/>\n        tar)<br \/>\n                echo &#8220;Running tape backup using tar tool&#8230;&#8221;<br \/>\n                ;;<br \/>\n        *)<br \/>\n        \t    echo &#8220;Backup shell script utility&#8221;<br \/>\n                echo &#8220;Usage: $0 {sql|sync|tar}&#8221;<br \/>\n                echo &#8221;\tsql  : Run mySQL backup utility.&#8221;<br \/>\n                echo &#8221;\tsync : Run web server backup utility.&#8221;<br \/>\n                echo &#8221;\ttar  : Run tape backup utility.&#8221;\t;;<br \/>\nesac<br \/>\nSave and close the file. Run it as follows:<\/p>\n<p>chmod +x allinonebackup.sh<br \/>\n# run sql backup<br \/>\n.\/allinonebackup.sh sql<br \/>\n# Dump file system using tape device<br \/>\n.\/allinonebackup.sh tar<br \/>\n# however, the following will fail as patterns are case sensitive<br \/>\n# you must use command line argument tar and not TAR, Tar, TaR etc.<br \/>\n.\/allinonebackup.sh TAR<\/p>\n<p>#!\/bin\/sh<\/p>\n<p>echo &#8220;Please talk to me &#8230;&#8221;<br \/>\nwhile :<br \/>\ndo<br \/>\n  read INPUT_STRING<br \/>\n  case $INPUT_STRING in<br \/>\n        hello)<br \/>\n                echo &#8220;Hello yourself!&#8221;<br \/>\n                ;;<br \/>\n        bye)<br \/>\n                echo &#8220;See you again!&#8221;<br \/>\n                break<br \/>\n                ;;<br \/>\n        *)<br \/>\n                echo &#8220;Sorry, I don&#8217;t understand&#8221;<br \/>\n                ;;<br \/>\n  esac<br \/>\ndone<br \/>\necho<br \/>\necho &#8220;That&#8217;s all folks!&#8221;<br \/>\nOkay, so it&#8217;s not the best conversationalist in the world; it&#8217;s only an example!<br \/>\nTry running it and check how it works&#8230;<\/p>\n<p>$ .\/talk.sh<br \/>\nPlease talk to me &#8230;<br \/>\nhello<br \/>\nHello yourself!<br \/>\nWhat do you think of politics?<br \/>\nSorry, I don&#8217;t understand<br \/>\nbye<br \/>\nSee you again!<\/p>\n<p>That&#8217;s all folks!<\/p>\n<p>#!\/bin\/bash<\/p>\n<p>MENU=&#8221;<br \/>\n1   Date and Time<br \/>\n2   Calendar for current month<br \/>\n3   quit<br \/>\n&#8221;<\/p>\n<p>while true; do<br \/>\n  clear<br \/>\n  echo &#8220;$MENU&#8221;<br \/>\n  echo -n &#8220;Please make your choice: &#8221;<br \/>\n  read INPUT # Read user input and assign it to variable INPUT<\/p>\n<p>  case $INPUT in<br \/>\n    1)<br \/>\n    date<br \/>\n    echo press ENTER to continue<br \/>\n    read<br \/>\n    ;;<br \/>\n    2)<br \/>\n    cal<br \/>\n    echo press ENTER to continue<br \/>\n    read<br \/>\n    ;;<br \/>\n    3|q|Q) # If user presses 3, q or Q we terminate<br \/>\n    exit 0<br \/>\n    ;;<br \/>\n    *) # All other user input results in an usage message<br \/>\n    clear<br \/>\n    echo Please choose alternatves 1, 2 or 3<br \/>\n    sleep 2<br \/>\n    ;;<br \/>\n  esac<\/p>\n<p>done<\/p>\n<p>!\/bin\/sh<\/p>\n<p>FRUIT=&#8221;apple&#8221;<\/p>\n<p>case &#8220;$FRUIT&#8221; in<br \/>\n   &#8220;apple&#8221;) echo &#8220;Apple pie is quite tasty.&#8221;<br \/>\n   ;;<br \/>\n   &#8220;banana&#8221;) echo &#8220;I like banana nut bread.&#8221;<br \/>\n   ;;<br \/>\n   &#8220;kiwi&#8221;) echo &#8220;New Zealand is famous for kiwi.&#8221;<br \/>\n   ;;<br \/>\nesac<\/p>\n<p>#!\/bin\/sh<br \/>\necho &#8220;Enter a character&#8221;<br \/>\nread var<br \/>\ncase $var in<br \/>\n[a-z])<br \/>\n   echo &#8220;You entered a lower case alphabet.&#8221;<br \/>\n      ;;<br \/>\n[A-Z])<br \/>\n     echo &#8220;You entered a upper case alphabet.&#8221;<br \/>\n      ;;<br \/>\n[0-9])<br \/>\n     echo &#8221; You entered a digit.&#8221;<br \/>\n      ;;<br \/>\n?)<br \/>\n     echo &#8221; You entered a speical sysmbol.&#8221;<br \/>\n      ;;<br \/>\n*)<br \/>\n     echo &#8221; You entered more than one character.&#8221;<br \/>\n      ;;<br \/>\nesac<\/p>\n<p>root@cluster1 shell]# .\/case.sh<br \/>\nEnter a character<br \/>\na<br \/>\nYou entered a lower case alphabet.<br \/>\n[root@cluster1 shell]# .\/case.sh<br \/>\nEnter a character<br \/>\nA<br \/>\nYou entered a lower case alphabet.<br \/>\n[root@cluster1 shell]# .\/case.sh<br \/>\nEnter a character<br \/>\nasfhadad<\/p>\n<p>=============================================================================================================================<\/p>\n<p>=================================================================================================================================================<br \/>\nQuick Reference<br \/>\nThis is a quick reference guide to the meaning of some of the less easily guessed commands and codes.<br \/>\nCommand\tDescription\tExample<br \/>\n&#038;\tRun the previous command in the background\tls &#038;<br \/>\n&#038;&#038;\tLogical AND\tif [ &#8220;$foo&#8221; -ge &#8220;0&#8221; ] &#038;&#038; [ &#8220;$foo&#8221; -le &#8220;9&#8221;]<br \/>\n||\tLogical OR\tif [ &#8220;$foo&#8221; -lt &#8220;0&#8221; ] || [ &#8220;$foo&#8221; -gt &#8220;9&#8221; ] (not in Bourne shell)<br \/>\n^\tStart of line\tgrep &#8220;^foo&#8221;<br \/>\n$\tEnd of line\tgrep &#8220;foo$&#8221;<br \/>\n=\tString equality (cf. -eq)\tif [ &#8220;$foo&#8221; = &#8220;bar&#8221; ]<br \/>\n!\tLogical NOT\tif [ &#8220;$foo&#8221; != &#8220;bar&#8221; ]<br \/>\n$$\tPID of current shell\techo &#8220;my PID = $$&#8221;<br \/>\n$!\tPID of last background command\tls &#038; echo &#8220;PID of ls = $!&#8221;<br \/>\n$?\texit status of last command\tls ; echo &#8220;ls returned code $?&#8221;<br \/>\n$0\tName of current command (as called)\techo &#8220;I am $0&#8221;<br \/>\n$1\tName of current command&#8217;s first parameter\techo &#8220;My first argument is $1&#8221;<br \/>\n$9\tName of current command&#8217;s ninth parameter\techo &#8220;My ninth argument is $9&#8221;<br \/>\n$@\tAll of current command&#8217;s parameters (preserving whitespace and quoting)\techo &#8220;My arguments are $@&#8221;<br \/>\n$*\tAll of current command&#8217;s parameters (not preserving whitespace and quoting)\techo &#8220;My arguments are $*&#8221;<br \/>\n-eq\tNumeric Equality\tif [ &#8220;$foo&#8221; -eq &#8220;9&#8221; ]<br \/>\n-ne\tNumeric Inquality\tif [ &#8220;$foo&#8221; -ne &#8220;9&#8221; ]<br \/>\n-lt\tLess Than\tif [ &#8220;$foo&#8221; -lt &#8220;9&#8221; ]<br \/>\n-le\tLess Than or Equal\tif [ &#8220;$foo&#8221; -le &#8220;9&#8221; ]<br \/>\n-gt\tGreater Than\tif [ &#8220;$foo&#8221; -gt &#8220;9&#8221; ]<br \/>\n-ge\tGreater Than or Equal\tif [ &#8220;$foo&#8221; -ge &#8220;9&#8221; ]<br \/>\n-z\tString is zero length\tif [ -z &#8220;$foo&#8221; ]<br \/>\n-n\tString is not zero length\tif [ -n &#8220;$foo&#8221; ]<br \/>\n-nt\tNewer Than\tif [ &#8220;$file1&#8221; -nt &#8220;$file2&#8221; ]<br \/>\n-d\tIs a Directory\tif [ -d \/bin ]<br \/>\n-f\tIs a File\tif [ -f \/bin\/ls ]<br \/>\n-r\tIs a readable file\tif [ -r \/bin\/ls ]<br \/>\n-w\tIs a writable file\tif [ -w \/bin\/ls ]<br \/>\n-x\tIs an executable file\tif [ -x \/bin\/ls ]<br \/>\nparenthesis:<br \/>\n( &#8230; )\tFunction definition\tfunction myfunc() { echo hello }<\/p>\n<p>Quiz: ShellCheck is aware of many common usage problems. Are you?<\/p>\n<p>find . -name *.mp3<br \/>\nsudo echo 3 > \/proc\/sys\/vm\/drop_caches<br \/>\nPS1=&#8217;\\e[0;32m\\$\\e[0m &#8216;<br \/>\nfind . | grep &#8220;*.mp3&#8221;<br \/>\n[ $n > 7 ]<br \/>\n[[ $n > 7 ]]<br \/>\ntr &#8216;A-Z&#8217; &#8216;a-z&#8217;<br \/>\ncmd 2>&#038;1 > log<br \/>\narray=(1, 2, 3)<br \/>\necho $10<br \/>\n[[ $a=$b ]]<br \/>\n[[ $a = $b ]]<br \/>\nprogress=$((i\/total*100))<br \/>\ntrap &#8220;echo \\&#8221;Time used: $SECONDS\\&#8221;&#8221; EXIT<br \/>\nfind dir -exec cp {} \/backup &#038;&#038; rm {} \\;<br \/>\n[[ $keep = [yY] ]] &#038;&#038; mv file \/backup || rm file<\/p>\n<p>ShellCheck gives more helpful messages for many Bash syntax errors<\/p>\n<p>Bash says\tShellCheck points to the exact position and says<br \/>\n: command not found\tLiteral carriage return. Run script through tr -d \u2018\\r\u2019<br \/>\nunexpected token: `fi\u2019\tCan\u2019t have empty then clauses (use \u2018true\u2019 as a no-op)<br \/>\nunexpected token `(\u2018\tShells are space sensitive. Use \u2018< <(cmd)', not '<<(cmd)'\nunexpected token `(\u2018\t\u2018(\u2018 is invalid here. Did you forget to escape it?\necho foo: command not found\tThis is a &nbsp;. Delete it and retype as space.\n \n  \nShellCheck suggests style improvements\n\nCode\tShellCheck suggestion\nbasename \"$var\"\tUse parameter expansion instead, such as ${var##*\/}\nls | grep 'mp3$'\tDon\u2019t use ls | grep. Use a glob or a for loop with a condition.\nexpr 3 + 2\tUse $((..)), ${} or [[ ]] in place of antiquated expr.\ncat foo | grep bar\tUseless cat. Consider \u2018cmd < file | ..' or 'cmd file | ..' instead.\nlength=$(echo \"$var\" | wc -c\")\tSee if you can use ${#variable} instead\n\n\n\nShellCheck recognizes common but wrong attempts at doing things\n\nCode\tShellCheck tip\nvar$n=42\tFor indirection, use (associative) arrays or \u2018read \u201cvar$n\u201d <<< \"value\"'\".\n(Bash says \u201cvar3=42: command not found\u201d)\n${var$n}\tTo expand via indirection, use name=\u201dfoo$n\u201d; echo \u201c${!name}\u201d \n(Bash says \u201cbad substitution\u201d. )\necho 'It\\'s time'\tAre you trying to escape that single quote? echo \u2018You\u2019\\\u201dre doing it wrong\u2019\n(Bash says \u201cunexpected end of file\u201d)\n[ grep a b ]\tUse \u2018if cmd; then ..\u2019 to check exit code, or \u2018if [[ $(cmd) == .. ]]\u2019 to check output\n(Bash says \u201c[: a: binary operator expected\u201d)\nvar=grep a b\tTo assign the output of a command, use var=$(cmd)\n(Bash says \u201ca: command not found\u201d)\n\n\n\n=================================================================================================================================================\n<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Shell program<\/p>\n<p>View System Date, Calender<\/p>\n<p>Calender<\/p>\n<p>[root@cluster1 ~]# cal April 2015 Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30<\/p>\n<p>[root@cluster1 ~]# cal 7 2015 July [&#8230;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[47],"tags":[],"_links":{"self":[{"href":"https:\/\/mohan.sg\/index.php?rest_route=\/wp\/v2\/posts\/4698"}],"collection":[{"href":"https:\/\/mohan.sg\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/mohan.sg\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/mohan.sg\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/mohan.sg\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=4698"}],"version-history":[{"count":3,"href":"https:\/\/mohan.sg\/index.php?rest_route=\/wp\/v2\/posts\/4698\/revisions"}],"predecessor-version":[{"id":4711,"href":"https:\/\/mohan.sg\/index.php?rest_route=\/wp\/v2\/posts\/4698\/revisions\/4711"}],"wp:attachment":[{"href":"https:\/\/mohan.sg\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=4698"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/mohan.sg\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=4698"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/mohan.sg\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=4698"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}