Linux Server Shell Programming learning notes

Source: Internet
Author: User
Tags binary to decimal chop echo command save file

The introduction to shell scripting is what this article is about, and we can use any type of text editor, such as Gedit, Kedit, Emacs, VI, to write the shell script, which must begin with the following line (must be placed on the first line of the file):

The code is as follows Copy Code

#!/bin/sh

... Note: It is best to use "!/bin/bash" instead of "!/bin/sh", if you use the TC Shell to TCSH, the other is similar.

The symbol #! is used to tell the system to execute the sell script, and this example uses/bin/sh. After the edit is finished and saved, if you want to execute the shell script, you must first make it executable:

chmod +x filename Thereafter, in the directory where the shell script is located, enter./filename to execute the shell script.

Some special symbols in the shell

A []

Shell off function

If you've written more complex shell scripts, you'll find that you might have used the same code in several places, and it would be much easier if you used the function. The approximate function is as follows:

The code is as follows Copy Code
functionname ()
{
# inside the ' body ' is the ' the ' the ' the ' the ' the ' the ' the '
# $ second ...
Body
}

You need to declare the function at the beginning of each script.

Here is a shell script called Xtitlebar, which can change the name of the terminal window. This uses a function called Help, which was used two times in a shell script:

The code is as follows Copy Code

#!/bin/sh
# Vim:set sw=4 ts=4 et:
Help ()
{
Cat << Help
Xtitlebar--Change the name of a xterm, gnome-terminal or KDE konsole
Usage:xtitlebar [-h] "String_for_titelbar"
OPTIONS:-H Help text
Example:xtitlebar "CVS"
Help
Exit 0
}
# in case of an error or if-h is given we call the function Help:
[-Z ' $] && Help
["$" = "-H"] && Help
# Send the escape sequence to the xterm Titelbar:
Echo-e "33]0;$107"

#在shell脚本中提供帮助是一种很好的编程习惯, it is convenient for other users (and themselves) to use and understand scripts.

Command line arguments

We've seen special variables such as $* and $ $, which contain the parameters that the user enters from the command line. So far, we've only learned a few simple command-line syntax (such as some mandatory arguments and the-H option to view Help). But when writing more complex programs, you may find that you need more customization options. The usual practice is to add a minus sign before all optional parameters, followed by the value of the parameter (such as the filename).

There are many ways to analyze input parameters, but the following examples of case expressions are certainly a good way to go.

The code is as follows Copy Code

#!/bin/sh

Help ()
{
Cat << Help
This is a generic command line parser demo.
USAGE example:cmdparser-l hello-f---somefile1 somefile2
Help
Exit 0
}

While [-N ' $]; Todo
Case is in
-h) Help;shift 1;; # function Help is called
-f) Opt_f=1;shift 1;; # variable Opt_f is set
-L) Opt_l=$2;shift 2;; # L takes a argument-> shift by 2
-Shift;break;; # End of options
-*) echo "error:no such option $. -h for help; exit 1;;
*) break;;
Esac
Done

echo "Opt_f is $opt _f"
echo "opt_l is $opt _l"
echo "The ' is $"
echo "2nd Arg is $"

You can run the script like this:

The code is as follows Copy Code

Cmdparser-l hello-f---somefile1 somefile2


The returned results are as follows:

Opt_f is 1
opt_l is Hello
Is-somefile1 of the A-arg
2nd Arg is Somefile2

How does this shell script work? The script first loops through all the input command-line arguments, compares the input parameter with the case expression, sets a variable if it matches, and removes the parameter. According to the practice of UNIX systems, the first input should be an argument containing a minus sign.

Shell Script Example

General programming steps

Now let's discuss the general steps to write a script. Any good script should have help and input parameters. Writing a framework script (framework.sh), which contains the framework structure required by most scripts, is a very good idea. This way, when we start writing a new script, we can first execute the following command:

The code is as follows Copy Code

CP framework.sh MyScript

And then insert your own function.

Let's take a look at the following two examples.

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:

The code is as follows Copy Code

#!/bin/sh
# Vim:set sw=4 ts=4 et:
Help ()
{
Cat << Help

b2d-Convert binary to Decimal

usage:b2d [-h] Binarynum

OPTIONS:-H Help text

example:b2d 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 ' "$" | Sed ' s///g ' | Wc-c '
# 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
   if [-Z "$ " ]; Then
      # empty string
      rval= ""
       return
   fi
   # WC puts some spaces behind the output this is why we need SED:
   numofchar= ' echo-n ' $ | wc-c | sed ' s///g '
   if ["$numofchar" = "1"]; then
      # only one char in string
      rval= '
  & nbsp;   return
   fi
   numofcharminus1= ' expr $numofchar-' 1 '
   # Now cut all but the last char:
   rval= ' echo-n ' $ | cut-b-$numofcharminus 1 '
   #原来的 rval = ' Echo-n ' | Error Cut-b 0-${numofcharminus1} ' run time.
   #原因是cut从1开始计数, should be cut-b 1-${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"

#该shell脚本使用的算法是利用十进制和二进制数权值 (1,2,4,8,16,..), such as binary "10″ can be converted to decimal:

The code is as follows Copy Code

0 * 1 + 1 * 2 = 2

In order to get a single binary number, we used the Lastchar function. The function calculates the number of characters using WC–C and then uses the Cut command to remove the end of a character. The function of the chop function is to remove the last character.

File Circulation reprint

You may have the need to do this all the time: Save all the messages you send to a file. But after a few months, the file can become so large that the file's access slows down, and the following shell script Rotatefile solves the problem. This script can rename the mail save file (assuming Outmail) as OUTMAIL.1, and the original OUTMAIL.1 become outmail.2, etc. ...

The code is as follows Copy Code

#!/bin/sh
# Vim:set sw=4 ts=4 et:

Ver= "0.1"
Help ()
{
Cat << Help
Rotatefile--Rotate the file name
Usage:rotatefile [-h] FileName
OPTIONS:-H Help text
Example:rotatefile out

This is e.g rename out.2 to Out.3, Out.1 to Out.2, out to OUT.1[BR]
and create an empty out-file

The max number is 10
Version $ver
Help
Exit 0
}

Error ()
{
echo "$"
Exit 1
}

While [-N ' $]; Todo
Case is in
-h) Help;shift 1;;
-) break;;
-*) echo "error:no such option $. -h for help; exit 1;;
*) break;;
Esac
Done

# input Check:
If [-Z "$"]; Then
Error "Error:you must specify a file, use-h for help"
Fi

Filen= "$"
# Rename any. 1,. 2 etc File:
For N in 9 8 7 6 5 4 3 2 1; Todo
If [-F "$filen. $n"]; Then
p= ' expr $n + 1 '
echo "MV $filen. $n $filen. $p"
MV $filen. $n $filen. $p
Fi
Done

# Rename the original file:
If [-F "$filen"]; Then
echo "MV $filen $filen. 1"
MV $filen $filen. 1
Fi

echo Touch $filen
Touch $filen

How does this shell script work? After detecting that a user provided a filename, start with a loop of 9 to 1; file name. 9 Rename to filename. 10, filename. 8 rename to filename. 9. ... Wait a minute. After the loop completes, name the original file as the filename. 1, and create an empty file with the same name as the original file (Touch $filen)

Script debugging

The simplest way to debug is of course to use the echo command. You can print variable values with echo in any place where you suspect it is wrong, which is why most shell programmers spend 80% of their time debugging. The advantage of a shell script is that there is no need to recompile, and it doesn't take much time to insert an echo command.

The shell also has a true debug mode, and if the script "Strangescript" goes wrong, you can use the following command to debug:

The code is as follows Copy Code

Sh-x strangescript7

The above command executes the script and displays the values of all variables.

There is also a pattern in the shell script that does not execute the script to check only the syntax, as follows:

The code is as follows Copy Code

Sh-n Your_script


This command returns all syntax errors.

We hope you can start writing your own shell script now and enjoy the fun!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.