Linux Shell script basics if you only look at the previous theoretical section, although there are some examples, but it is not systematic enough, here we will show you a specific example of Linux Shell script programming, to help you learn and improve the basics of Linux Shell.
Part 1 instances
Now let's discuss the general steps for writing a script. Any excellent script should have help and input parameters. And write a pseudo script (Framework. Sh) that contains the framework structure required by most scripts, which is a very good idea. At this time, when writing a new script, we only need to execute the Copy command:
CP framework. Sh myscript
Then insert your own function.
Let's look at another example:
Binary to decimal conversion
The script b2d converts the binary number (such as 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
Will return 58
Help
Exit 0
}
Error ()
{
# Print an error and exit
Echo "$1"
Exit 1
}
Lastchar ()
{
# Return the last character of a string in $ rval
If [-z "$1"]; then
# Empty string
Rval = ""
Return
Fi
# WC puts some space behind the output this is why we need sed:
Numofchar = 'echo-n "$1" | WC-c | SED's // g''
# Now cut out the last char
Rval = 'echo-n "$1" | cut-B $ numofchar'
}
Chop ()
{
# Remove the last character in string and return it in $ rval
If [-z "$1"]; then
# Empty string
Rval = ""
Return
Fi
# WC puts some space behind the output this is why we need sed:
Numofchar = 'echo-n "$1" | 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 the last CHAR:
Rval = 'echo-n "$1" | cut-B 0-$ {numofcharminus1 }'
}
While [-n "$1"]; do
Case $1 in
-H) Help; shift 1; # function help is called
--) Shift; break; # End of options
-*) Error "error: no such option $1.-H for help ";;
*) Break ;;
Esac
Done
# The main program
Sum = 0
Weight = 1
# One Arg must be given:
[-Z "$1"] & Help
Binnum = "$1"
Binnumorig = "$1"
While [-n "$ binnum"]; do
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"
TheAlgorithmIt uses decimal and binary values (, 16,...). For example, binary "10" can be converted to decimal:
0*1 + 1*2 = 2
To obtain a single binary number, we use the lastchar function. This function uses WC-C to calculate the number of characters, and then uses the cut command to retrieve the last character. The Chop function removes the last character.
This Linux Shell script instance helps us complete the conversion. Next time we will give an example of a file loop Program .