Linux Shell Script Basic Learning Details (full version) two

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

Learn more about Linux Shell Scripting Basics (v) Linux Shell Script Foundation before we introduce the control flow of the Linux shell script, there is still a part of it that doesn't say anything about here document continues here.
The Linux Shell Script Foundation has been divided into several parts, where the content of the control process is immediately finished, this is the last part about here document, where the example is a little bit more complex, we slowly analyze this complex Linux shell script.

6. Here documents

When you want to pass a few lines of text to a command, here documents is a good way to see that the word is suitable for translation. It is useful to write a piece of helpful text for each script, at which point we don't have to use the Echo function to output a row of lines if we have the four. A "Here document" begins with <<, followed by a string, which must also appear at the end of here document. Here is an example where we rename multiple files and use the here documents to print help:

#!/bin/sh

# We have less than 3 arguments. Print the Help text:

If [$#-lt 3]; Then

Cat <

Ren--Renames a number of files using SED regular expressions

Usage:ren ' regexp ' replacement ' files ...

Example:rename all *. HTM files in *.html:

ren ' htm$ ' html ' *. Htm

Help

Exit 0

Fi

Old= "$"

New= "$"

# The SHIFT command removes one argument from the list of

# command line arguments.

Shift

Shift

# $* contains now all the files:

for file in $*; Do

If [-F "$file"]; Then

Newfile= ' echo ' $file | Sed "s/${old}/${new}/g" '

If [-F "$newfile"]; Then

echo "ERROR: $newfile exists already"

Else

echo "Renaming $file to $newfile ..."

MV "$file" "$newfile"

Fi

Fi

Done

This is a complicated example. Let's discuss it in detail. The first if expression determines whether the input command-line argument is less than 3 (the special variable $# represents the number of parameters included). If the input parameter is less than 3, the help text is passed to the Cat command, which is then printed on the screen by the cat command. The program exits after printing the help text. If the input parameter is equal to or greater than 3, we assign the first parameter to the variable old and the second parameter to the variable new. Next, we use the shift command to remove the first and second arguments from the argument list, so that the third argument becomes the first parameter of the argument list $*. Then we start the loop, and the command-line argument list is assigned to the variable $file one by one. We then determine if the file exists and, if it exists, it is searched and replaced by the SED command to generate a new file name. The command result in the backslash is then assigned to NewFile. So that we can achieve our goal: to get the old file name and the new filename. Then use the MV command to rename it. This will clear up this complex Linux shell script.

Learn more about Linux Shell Scripting Basics (vi) Linux Shell Script Basic Learning we're almost done here, and the last part is about the function, which is about the basic part, and then there are examples.

4) function

If you write a slightly more complex program, you will find that the same code may be used in several places in the program, and you will find that if we use the function, it will be much easier. This is what a function looks like:

functionname ()

{

# inside the body argument given to the function

# The second ...

Body

}

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

Here is a script called Xtitlebar that you can use to change the name of the terminal window.

A function called Help is used here. As you can see, this defined function is used two times.

#!/bin/sh

# Vim:set sw=4 ts=4 et:

Help ()

{

Cat <

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 error or if-h are given we call the function Help:

[-Z "$"] && Help

["$" = "-H"] && Help

# Send the escape sequence to the xterm Titelbar:

Echo-e "33]0;$107"

#

Providing help in a script is a good programming habit, which makes it easier for other users (and you) to use and understand scripts.

Command-line arguments

We've seen $* and $ $ ... $9 and other special variables that contain the parameters that the user entered from the command line. So far, we've only learned a few simple command-line syntax (such as some mandatory parameters and the-h option for viewing help). But when you're writing more complex programs, you may find that you need more custom options. A common practice is to add a minus sign before all optional arguments, followed by a parameter value (such as a file name)

There are many ways to analyze input parameters, but the following examples of using case expressions are a good idea.

#!/bin/sh

Help ()

{

Cat <

This was a generic command line parser demo.

USAGE example:cmdparser-l hello-f---somefile1 somefile2

Help

Exit 0

}

While [-N "$"]; Do

Case $ 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 an 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 "First Arg is $"

echo "2nd Arg is $"

You can run the script this way:

Cmdparser-l hello-f---somefile1 somefile2

The results returned are:

Opt_f is 1

opt_l is Hello

First ARG is-somefile1

2nd Arg is Somefile2

How does this script work? The script first loops through all the input command-line arguments, compares the input parameters to the case expression, sets a variable if the match, and removes the argument. According to the practice of UNIX systems, the first entry should be a parameter that contains a minus sign.

Learn more about Linux Shell Scripting Basics (vii) The knowledge of the basics of Linux shell scripting is finished, followed by two specific examples, where the first one about when the binary is forbidden is the conversion.
Linux shell Script Basic Learning this part if only look at the theoretical part of the previous, although there are some examples, but not enough system, here will be a concrete example to show you the Linux shell script programming to help you improve the Linux Shell Foundation learning and improve.
Part 2nd Example
Now let's discuss the general steps for writing a script. Any good script should have help and input parameters. and write a pseudo-script (framework.sh), which contains the framework structure that most scripts need, 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 one more example:
Conversion of binary to decimal
The script b2d converts the binary number (for example, 1101) to the corresponding decimal number. This is also an example of a mathematical operation with the expr command:

Copy CodeThe code is as follows: #!/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 wil L return to help exit 0} error () {# Print an error and exit Echo ' $ ' exit 1} lastchar () {# return the last character of a string in $rval if [-z] $ "; Then # empty string
Rval= "" Return fi # WC puts some space behind the output this 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 an IT in $rval if [-Z] $ []; then # empty string rval= "" Return F I
# WC puts some space behind the output this is why we need sed:
Numofchar= ' Echo-n ' | wc-c | Sed ' s///g ' if ["$numofchar" = "1"]; Then # one char in string rval= "" Return fi
numofcharminus1= ' expr $numofchar '-' 1 ' # now cut all, and the last char:
Rval= ' Echo-n ' | Cut-b 0-${numofcharminus1} '} while [-N "$"]; Do case $ 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"]; 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"

The algorithm used by the script is to take advantage of decimal and binary number weights (1,2,4,8,16,..), such as the binary "10" can be converted to decimal:
0 * 1 + 1 * 2 = 2
In order to get a single binary number we are using the Lastchar function. The function uses Wc–c to calculate the number of characters, and then uses the Cut command to remove the end character. The function of the chop function is to remove the last character.
This example of a Linux shell script has helped us with the conversion, and the next time we will be example a file loop program.
Learn more about Linux Shell Scripting Basics (eight)
The Linux shell Script Basic Learning example illustrates the conversion of decimal and binary, and here's the last example, the loop about the file, and how to debug it to end our course.

The previous instance of the Linux shell script is a description of the decimal and binary conversions, as well as an example of a file loop to end this part of the learning. Learners who believe that the basic learning of Linux shell scripts should be able to master some simple Linux shell script writing. File Recycling Program

Maybe you're one of those people who want to save all the sent messages to a file, but after a few months, the file can become so large that it slows down the file. The following script rotatefile can solve this problem. This script can rename the message to save the file (assuming outmail) is OUTMAIL.1, and for outmail.1 it becomes outmail.2 and so on ...

Copy CodeThe code is as follows: #!/bin/sh # vim:set sw=4 ts=4 et:ver= "0.1" help () {Cat < Rotatefile--Rotate the file name Usage:rotatefile [ -h] filename OPTIONS:-H Help text example:rotatefile out this would e.g rename out.2 to Out.3, Out.1 to Out.2 .1 and create an empty out-file the max number are version $ver help exit 0} error () {echo ' $ ' exit 1} While [-N ' $ 1 "]; Do case $ 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; do 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 ' $fi Len "]; Then echo "MV $filen $filen. 1" MV $filen $filen. 1 fi echo Touch $filen touch $filen

How does this script work? After detecting a file name provided by the user, we perform a 9 to 1 loop. File 9 is named 10, file 8 is renamed to 9, and so on. After the loop is complete, we name the original file 1 and create an empty file with the same name as the original file.

Debugging

The simplest debug command, of course, is to use the echo command. You can use Echo to print any variable value in any place where you suspect it is wrong. That's why most shell programmers spend 80% of their time debugging programs. The advantage of a shell program is that it doesn't need to be recompiled, and it doesn't take much time to insert an echo command.

The shell also has a real debug mode. If there is an error in the script "Strangescript", you can debug it this way:

Sh-x Strangescript

This executes the script and displays the values of all variables.

The shell also has a pattern that does not need to execute a script just to check the syntax. This can be used:

Sh-n Your_script

This will return all syntax errors

Linux Shell Script Basic Learning Details (full version) two

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.