Linux Server Shell programming learning notes

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

Shell is a system user interface that provides an interface for users to interact with the kernel. It receives user-input commands and sends them to the kernel for execution. In fact, Shell is a command interpreter that explains the commands entered by the user and sends them to the kernel.

Getting started with Shell script programming is what we will introduce in this article. We can use any text editor, such as gedit, kedit, emacs, and vi to write shell scripts, it must start with the following line (the first line of the file must be placed ):

The Code is as follows: Copy code

#! /Bin/sh

... Note: it is best to use "! /Bin/bash "instead of"! /Bin/sh ", if you use tc shell to change to tcsh, others are similar.

Symbol #! The program used to tell the system to execute the scripts. This example uses/bin/sh. After editing and saving, if you want to execute the shell script, you must first make it executable:

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

Some special symbols in Shell

A []

Shell departure Function

If you have written complicated shell scripts, you may find that the same code may be used in several places. In this case, it is much easier to use functions. The functions are roughly as follows:

The Code is as follows: Copy code
Functionname ()
{
# Inside the body $1 is the first argument given to the function
#$2 the second...
Body
}

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

The following is a shell script named xtitlebar, which can change the terminal window name. Here we use a function named help, which is used twice in the 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 an 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 is given we call the function help:
[-Z "$1"] & help
["$1" = "-h"] & help
# Send the escape sequence to change the xterm titelbar:
Echo-e "33] 0; $107"

# It is a good programming habit to help other users (and themselves) use and understand scripts.

Command Line Parameters

We have seen $ * and $1, $2... $9 and other special variables include the parameters you input from the command line. So far, we have only learned some simple command line syntax (such as some mandatory parameters and the-h option for viewing help ). However, when writing more complex programs, you may find that you need more custom options. The common practice is to add a minus sign before all optional parameters, followed by a parameter value (such as a file name ).

There are many ways to analyze input parameters, but the example using the case expression below is undoubtedly a good method.

The Code is as follows: Copy code

#! /Bin/sh

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

While [-n "$1"]; do
Case $1 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 $1.-h for help"; exit 1 ;;
*) Break ;;
Esac
Done

Echo "opt_f is $ opt_f"
Echo "opt_l is $ opt_l"
Echo "first arg is $1"
Echo "2nd arg is $2"

You can run the script like this:

The Code is as follows: Copy code

Extends parser-l hello-f ---somefile1 somefile2


The returned results are as follows:

Opt_f is 1
Opt_l is hello
First arg is-somefile1
2nd arg is somefile2

How does this shell script work? The script first loops through all input command line parameters and compares the input parameters with the case expression. If the input parameters match, a variable is set and the parameter is removed. According to the Convention of the unix system, the first input should be the parameter containing the minus sign.

Shell script example

General programming steps

Now let's discuss the general steps for writing a script. Any excellent script should have help and input parameters. Write a framework script (framework. sh) that contains the framework structure required by most scripts. It is a very good idea. In this way, when writing a new script, you can first execute the following command:

The Code is as follows: Copy code

Cp framework. sh myscript

Then insert your own function.

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

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:

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
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" | sed's // G' | wc-C'
# 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-$ numofcharminus1'
# The original rval = 'echo-n "$1" | cut-B 0-$ {numofcharminus1} 'encountered an error during running.
# The reason is that cut starts counting from 1. It should be cut-B 1-$ {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"

# The shell script uses decimal and binary weights (, 16,...). For example, binary "10" can be converted to decimal:

The Code is as follows: Copy code

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.

Reprinting objects cyclically

You may want to do this all the time: Save all sent emails to a file. However, after a few months, the file may become so large that the access speed of the file will be slow. The following shell script rotatefile can solve this problem. This script can rename the email storage file (assuming outmail) to outmail.1, and the original outmail.1 is changed to outmail.2 and so on...

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 will 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 "$1"
Exit 1
}

While [-n "$1"]; do
Case $1 in
-H) help; shift 1 ;;
--) Break ;;
-*) Echo "error: no such option $1.-h for help"; exit 1 ;;
*) Break ;;
Esac
Done

# Input check:
If [-z "$1"]; then
Error "ERROR: you must specify a file, use-h for help"
Fi

Filen = "$1"
# 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 "$ 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 file name is provided by the user, perform a loop of 9 to 1. Rename file name. 9 to file name. 10, and rename file name. 8 to file name. 9 ...... And so on. After the loop ends, name the original file as file name. 1 and create an empty file (touch $ filen) with the same name as the original file)

Script debugging

The simplest debugging method is to use the echo command. You can use echo to print variable values wherever possible, which is why most shell Programmers spend 80% of their time debugging. The benefit of Shell scripts is that it does not take much time to insert an echo command without recompilation.

Shell also has a real debugging mode. If the script "strangescript" has an error, run the following command to debug it:

The Code is as follows: Copy code

Sh-x strangescript7

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

In the shell script, there is also a mode for checking only the syntax without executing the script. The command is as follows:

The Code is as follows: Copy code

Sh-n your_script


This command returns all syntax errors.

We hope that you can now write your own shell scripts and enjoy it!

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.