Now let's discuss the general steps to write a script. Any good script should have help and input parameters. and write a pseudo script (framework.sh) that contains the framework structure that most scripts require, and is a very good idea. At this point, we only need to execute the copy command when writing a new script:
CP framework.sh MyScript
And then insert your own function.
Let's look at two more examples:
1, binary to decimal conversion
The script b2d converts the binary number (for example, 1101) to the corresponding decimal number. This is also an example of a mathematical operation using the expr command:
#!/bin/sh
# Vim:set sw=4 ts=4 et:
Help ()
{
Cat <
B2H-Convert binary to Decimal
USAGE:B2H [-h] Binarynum
OPTIONS:-H Help text
EXAMPLE:B2H 111010
would return 58
Help
Exit 0
}
Error ()
{
# Print an error and exit
echo "$"
Exit 1
}
Lastchar ()
{
# return ' last character ' a string in $rval
If [-Z "$"]; Then
# empty string
Rval= ""
Return
Fi
# WC puts some space behind the ' output ' is why we need sed:
Numofchar= ' Echo-n ' "$" | wc-c | Sed ' s///g '
# now cut out of the last Char
Rval= ' Echo-n ' "$" | Cut-b $numofchar '
}
Chop ()
{
# Remove the last character in string and return it in $rval
This paper url:http://www.bianceng.cn/os/linux/201410/45612.htm
If [-Z "$"]; Then
# empty string
Rval= ""
Return
Fi
# WC puts some space behind the ' output ' is why we need sed:
Numofchar= ' Echo-n ' "$" | wc-c | Sed ' s///g '
If ["$numofchar" = "1"]; Then
# only one char in string
Rval= ""
Return
Fi
numofcharminus1= ' expr $numofchar '-"1"
# now cut all but char:
Rval= ' Echo-n ' "$" | Cut-b 0-${numofcharminus1} '
}
While [-N ' $]; Todo
Case is in
-h) Help;shift 1;; # function Help is called
-Shift;break;; # End of options
-*) Error "error:no such option $. -H for help ";;
*) break;;
Esac
Done
# The main program
Sum=0
Weight=1
# One ARG must be given:
[-Z ' $] && Help
Binnum= "$"
Binnumorig= "$"
While [-N "$binnum"]; Todo
Lastchar "$binnum"
If ["$rval" = "1"]; Then
sum= ' expr ' $weight ' "+" "$sum"
Fi
# Remove the last position in $binnum
Chop "$binnum"
Binnum= "$rval"
weight= ' expr ' $weight ' "*" 2 '
Done
echo "Binary $binnumorig is decimal $sum"