Getting Started with Shell programming under Linux

Source: Internet
Author: User
Tags case statement echo date

Typically, we enter commands from the command line each time to get a response from the system. This is obviously inefficient when we need to enter commands one after the other and finally get the results. To achieve this, we usually use shell programs or shell scripts.

First, Introduction

Shell programming has many features, such as C and other programming languages, but it is not as complex as a language. A shell program is a series of Linux commands and utilities placed in a file that, when executed, interprets and executes each command from Linux one after the other.

Let's look at a simple shell program:

1. First create a file with the following name, named date, which is stored in the bin subdirectory of the directory.

#Program Date

#usageto:: Show the date in this (note)

echo "Mr $USER, Today is:"

echo Date "+%b%d%a"

echo "Whish a lucky day!"

2, after editing the file it can not execute, we need to set it executable permissions. Use the following command:

chmod +x Date

With the above procedure, we can execute the shell program just as we would with the LS command.

[[Email protected] bin]$ Date

Mr.beichen,today is:

January Friday

Whish a lucky day!

In order to be able to execute this program in any directory, you can add this directory in the bin to the path.

[Email protected] bin]$ path= $PATH: $HOME/bin

(Note: The $home here instead of the/home/beichen, and the bin directory is a directory built by itself)

Another way to execute date is to pass it as a parameter to the shell command:

[[email protected]/]$ Bash date

Mr.beichen,today is:

January Friday

Whish a lucky day!

Although we used chmod +x date to set date to executable in front of it, it doesn't really matter if it's not set, but it needs to be told to the system that it is an executable script before executing it in Linux.

[[email protected]/]$. Date

Mr.beichen,today is:

January Friday

Whish a lucky day!

That is, precede the date with a dot "." and use a space separated from the file name of the following shell script. Of course, this is not recommended.

Second, shell parameters

As with the LS command can accept directories and so on as its parameters, in shell programming can also use parameters. The shell has positional parameters and internal parameters.

1. Position parameters

The parameters provided by the system are called positional parameters. The value of the positional parameter can be obtained with $n, N is a number, if 1, that is, $ $. Similar to the C language, Linux will fragment the input command string and label each segment, starting with 0. The No. 0 number is the program name, which is the parameter passed to the program starting from 1. If $ $ represents the name of the program, $ $ represents the first parameter passed to the program, and so on.

2. Internal parameters

The $ A in the above process is an internal variable, which is required, and $ $ is optional. The same internal variables as $ A are as follows.

$#----The total number of arguments passed to the program

$? ----the previous code or shell program exits in the shell, returns 0 if normal exits, or a non-0 value.

$*----A string that consists of all the arguments passed to the program.

The following examples illustrate:

Create a program with the following P1:

echo "program name is $"

echo "There is totally $# parameters passed to the program"

echo "The last is $?"

echo "The parameters is $*"

The following results are performed:

[[email protected] bin]$ P1 This was a test program//Pass 5 parameters

Program name IS/HOME/BEICHEN/BIN/P1//give the full path and name of the application

There is totally 5 parameters passed to the total number of program//Parameters

The last is 0//program execution results

The parameters is an a test program//returns a string consisting of parameters
Let's write a simple delete program named del using the internal variables and positional parameters:

#name: Del

#author: Liangnian

#this program to compress a file to the dustbin

if test $#-eq 0

Then

echo "Please specify a file!"

Else

gzip//Compress files first

MV $1.gz $HOME/dustbin//move to Recycle Bin

echo "File $ is deleted!"

Fi

Three, variable expression

In the small program we wrote above we used a keyword test, which is actually an expression in the shell program? D? D comparison (test). We can easily finish the judgment by combining the IF and other conditional statements provided by the shell (which we will introduce later).

Its usage is as follows:

Test expression

The operator represented by the expression is a string operator, a numeric operator, a logical operator, and a file operator. Where the file operator is a unique operator of the shell, because the variables in the shell are strings, in order to achieve the purpose of manipulating the file, so it is provided with such an operator.

1. String comparison

Action: Test whether the string is equal, whether the length is zero, whether the string is null (NOTE: Bash distinguishes between 0-length strings and empty strings)

The commonly used character-wearing operators are:

= Compares whether two strings are the same, or "yes"! = Compares two strings for the same, and the other is Yes

-N compares whether the string length is greater than 0, or "yes" if it is greater than zero

-Z compares whether a string's piercing is equal to zero, or "yes" if it equals

2. Comparison of numbers

Unlike other programming languages, the test statement does not use the notation to express the size of the comparison, but instead uses an integer to represent these.

-eq equal

-ge greater than or equal to

-le less than or equal to

-ne Not equal to

-GT Greater than

-lt less than

3, logic operation! Inverse: A logical value that is opposite to a logical value

-A With (and): Two logical value is "Yes" return value is "yes", vice versa "no"

-O or (OR): Two logical values have a "yes" and the return value is "yes"

4. File operation

A file test expression is typically used to test the information of a file, typically by a script that determines whether a file should be backed up, copied, or deleted. Because the test has a lot of operators about the file, we only list some of the common ones.

-D object exists and returns a value of "Yes" for the directory

-F object exists and returns a value of "yes" to the file

-L object exists and returns a value of "yes" for symbolic connections

-R object exists and is readable the return value is "yes"

-S object exists and the length is nonzero the return value is "yes"

-W object is present and writable the return value is "yes"

-X object exists and executable returns a value of "yes"

File1? Cnt (-ot) file2 file 1 than file 2 new (old)

IV. Circular Structure Statements

Shell Common loop statements have a for loop, while loop, until loop

For loop

Syntax: for variable in list

Do

Operation

Done

Note: A variable is used inside a loop to refer to that object in the list of the currently-referred generations.

A list is an object that is to be manipulated inside a for loop, either as a string or as a file, or as a file name.

Example: Delete all. gz files in a trash bin

#delete all file with extension of "GZ" in the dustbin

For I in $HOME/dustbin/*.gz

Do

Rm? Cf $i

echo "$i has been deleted!"

Done

The results of the implementation are as follows:

[Email protected] Bin]$.f_rmgz

/home/beichen/dustbin/nessus-4.0.0.2.tar.gz has been deleted!

/home/beichen/dustbin/gftp-2.2.1.tar.gz has been deleted!

While loop

Syntax: while expression

Do

Operation

Done

As long as the while expression is true, the operation between do and done will continue.

Until cycle

Syntax: until expressions

Do

Operation

Done

Repeat the action between do and done until the expression is formed.

Cases:

#test until

#add from 1 to 100

Total=0

Num=0

Until Test num? Ceq 100

Do

Total= ' expr $total + $num '//Note that the quotation marks here are inverted

num= ' expr $num +1 '

Done

echo "The result is $total"

The results of the implementation are as follows:

[[email protected] bin] $until

The result is 5050!

V. Conditional statements

The conditional statements in shell programs mainly have if statements, case statements;

If statement

Syntax: if expression 1 Then

Operation

Elif Expression 2 Then

Operation

Elif Expression 3 Then

Operation

.....

Else

Operation

Fi

The end sign of if in Linux is the IF, in turn, is written as fi, whereas Elif is actually an abbreviation for else if

Where elif theoretically can have infinitely many.
Case statement

Syntax: Case string in

Value 1| value 2)

Operation::

Value 3| value 4)

Operation::

Value 5| value 6)

Operation::

*}

Operation::

Esac

The action of a case is that when the string is the same as a value, it executes the operation after that value. If the same operation is for multiple values, use the ' | ' Separates individual values. There are two "::" On the last side of each operation of the case, and the semicolon is required.

Cases:

Case $USER in

Beichen)

Echo "You are beichen!";;

Liangnian)

echo "You are Liangnian"; Notice there's only one semicolon.

echo "welcome!";; This is two semicolons.

Root

echo "You are Root!:echo welcome!";; Write two commands on one line, with a semicolon as the delimiter

*)

Echo "Who is $USER?";

Esac

Execution Result:

[Email protected] bin]$ test

You are Liangnian

welcome!

So much about the basics of shell programming, if you want to learn more about Shell programming, check out the relevant books

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.