CP6 Shell Logic and Arithmetic

1. How to do arithmetic in your shell script

problem : You need to do some simple arithmetic in your shell script

Solution: Use $(()) or let for integer arithmetic expressions

2.Branching on Conditions

Problem : You want to check if you have the right number of arguments and take actions accordingly.You need a branching construct.

Solution: If statement in bash is similar in apperance to that in other programming languages

3.Testing for File Characteristic

Problem:

You want to make your script robust by checking to see if your input file is there before reading from it;you would like to see if your output file has write permissions before writing to it; you would like to see if there is a directory there before you attempt to cd into it.How do you do all that in bash scripts?

Solution:

use the various file characteristic tests in the test command as part of your if statements.Your specific problems might be solved with scripting that looks something like this :

4.Testing for More Than One Thing

Problem

What if you want to test for more than one characteristic ? Do you have to nest your if statements?

Solution

Use the operations for logical AND(-a) and OR (-o) to combine more than one test in an expression.

if [-r $File -a -w $File]

will test to see that the file is both readable and writable

5.Testing for String Characteristics

Problem

You want your script to check the value of some strings before using them.The strings could be user input ,read from a file, or enviroment variables speed to your script.How do you do that with bash scripts?

Solution

  • using the single bracket if statement
  • see whether a variable has any text
  • see whether two variables are equal as strings.

[maxwell@DBAMAXWELL cp6]$ cat checkstr.sh
#!/bin/bash
#cookbook filename: checkstr
#
#if statement
# test a string to see if it has has length
#
#use the command line argument
VAR="$1"
#
if [ "$VAR" ]
then
    echo has text
else
    echo zero length
fi
#
if [-z "$VAR"]
then
    echo zero length
else
    echo has text
fi
[maxwell@DBAMAXWELL cp6]$ 

6.Testing for Equal

Problem

You want to check to see if two shell variables are equal,but there are two different test operators: -eq and = (or ==) .So which one should you use?

Solution

The type of comparison you need determines which operator you should use.Use the -eq operator for numeric comparisons and the equality primary = (or == ) for string comparisons

[maxwell@DBAMAXWELL cp6]$ vi strvsnum.sh
#!/bin/bash
# cookbook filename: strvsnum
#
# the old string vs. numeric comparison dilema
#
VAR1=" 05 "
VAR2="5"
printf "%s" "do they -eq as equal? "
if [ "$VAR1" -eq "$VAR2" ]
then    
    echo YES
else
    echo NO
fi  

printf "%s" "do they = as equal? "
if [ "$VAR1" -eq "$VAR2" ]
then
    echo YES
else
    echo NO
fi  

printf "%s" "do they = as equal? "
if [ "$VAR1" = "$VAR2" ]
then    
    echo YES
else
    echo NO
fi  
~                                                                                                                                                 
~                                                                                                                                                 
"strvsnum.sh" [New] 30L, 416C written                                                                                 
[maxwell@DBAMAXWELL cp6]$ ls -ltr
total 4
-rw-r--r-- 1 maxwell root 416 Mar 16 17:22 strvsnum.sh
[maxwell@DBAMAXWELL cp6]$ sh -x strvsnum.sh
+ VAR1=' 05 '
+ VAR2=5
+ printf %s 'do they -eq as equal? '
do they -eq as equal? + '[' ' 05 ' -eq 5 ']'
+ echo YES
YES
+ printf %s 'do they = as equal? '
do they = as equal? + '[' ' 05 ' -eq 5 ']'
+ echo YES
YES
+ printf %s 'do they = as equal? '
do they = as equal? + '[' ' 05 ' = 5 ']'
+ echo NO
NO
[maxwell@DBAMAXWELL cp6]$ sh strvsnum.sh   
do they -eq as equal? YES
do they = as equal? YES
do they = as equal? NO
[maxwell@DBAMAXWELL cp6]$ 

 

7.Testing with Pattern Matches

 Problem

You want to test a string not for a literal match,but to see if it fits a pattern.

Solution

if [[ "${MYFILENAME}" == *.jpg  ]]

 8.Testing with Regular Expressions

Problem

  • write a script to rename these files to something simple.

Solution

  • Use the regular expression matching of the =~ operator. the various parts of the pattern are available in the shell variable $BASH_REMATCH。Here is  the part of the script that deals with the pattern match:

[maxwell@DBAMAXWELL cp6]$ cat trackmatch.sh
#!/bin/bash
#cookbook filename : trackmatch
#
for CDTRACK in *
do
    if [[ "CDTRACK" =~ "([[:alpha:][:bank:]]*)-([[:digit:]]*) - (.*)$" ]]
    then
        echo Track ${BASH_REMATCH[2]} is ${BASH_REMATCH[3]}
        mv "$CDTRACK" "Track${BASH_REMATCH[2]}"
    fi
done
[maxwell@DBAMAXWELL cp6]$ sh trackmatch.sh
[maxwell@DBAMAXWELL cp6]$ 

9.Looping for a While

Problem

You want your shell script to perform some actions repeatedly as long as some condition is met

Solution

while (( COUNT < MAX ))

do 

          some stuff

          let COUNT++

done

---------------------------------------------------------

for filesystem-related conditions:

while [ -z "$LOCKFILE" ]

do 

        some things

 done

-------------------------------------------------------------

or for reading input:

while read lineoftext

do 

        process $lineoftext

done

----------------------------------------------------------------

10.Looping with a read

Problem

To clean up this directory it would be nice to get rid of all the scratch files, which are those files named in lines that begin with a question mark.

Solution

 11.Looping with a Count

Problem

you need to loop a fixed number of times.

Solution

[maxwell@DBAMAXWELL cp6]$ for (( i=0 ; i < 10 ; i++ )); do echo $i ; done
0
1
2
3
4
5
6
7
8
9
[maxwell@DBAMAXWELL cp6]$ 
 

[maxwell@DBAMAXWELL cp6]$ for i in 1 2 3 4 5 6 7 8 9 10
> do
>    echo $i
> done

1
2
3
4
5
6
7
8
9
10
[maxwell@DBAMAXWELL cp6]$

[maxwell@DBAMAXWELL cp6]$ for (( i=0 ; i+j < 10 ; i++, j++ ))
> do
>     echo $((i*j))
> done

0
1
4
9
16
[maxwell@DBAMAXWELL cp6]$ 

12.Branching Many Ways

Problem

You have a series of comparisons to make ,and the if /then/else is getting pretty long and repetitive.Isn't there an easier way?

Solution

case $FN in

        *.gif) gif2png $FN

                ;;

        *.png) pngOK $FN

                ;;

        *.jpg) jpg2gif $FN

                ;;

        *.tif | *.TIFF) tif2jpg $FN

                ;;

         *) printf "File not supported: %s" $FN

                 ;;

esac

The equivalent to this using if/then/else statements is:

if [[ $FN == *.gif ]]

then

        gif2png $FN

elif [[ $FN == *.png ]]

then

        pngOK $FN

elif [[ $FN == *.jpg ]]

then

        jpg2gif $FN

elif [[ $FN == *.tif || $FN == *.TIFF ]]

then

        tif2jpg $FN

else

        printf "File not supported: %s" $FN

fi

13. Parasing Command-Line Arguments

Problem

Solution

[maxwell@DBAMAXWELL cp6]$ cat dash.sh 
#!/bin/bash
#cookbook file: dash
#
#dashes - print a line of dashes
#
#options: # how many (default 72)
#         -c X use char X instead of dashes
#

LEN=72
CHAR='-'
while (( $# > 0 ))
do
    case $1 in
        [0-9]*) LEN=$1
            ;;
        -c) shift;
             CHAR=${1:--}
          ;;
       *) printf 'usage: %s [-c X] [#]\n' $(basename $0) >&2
          exit 2
          ;;
     esac
     shift
done
[maxwell@DBAMAXWELL cp6]$ 

14.Creating a Command-Line Calculator

Problem

You need more than just integer arithmetic,and you've never been very fond of RPN notation.How about a different approach to a command-line calculator?

Solution

Create a trivial command-line calculator using awk's built-in floating-point arithmetic expressions:

[maxwell@DBAMAXWELL cp6]$ cat calc
#!/bin/bash
# cookbook filename: func_calc
# Trivial command line calculator
function calc
{
    awk "BEGIN {print \"The answer is: \" $* }";
}
[maxwell@DBAMAXWELL cp6]$ 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值