Shell script programming Basics

Source: Internet
Author: User

Shell Introduction

Shell is simply a command parser that converts user-input commands into programs that can be executed by corresponding machines.

A Shell script is a text file (batch processing) that contains a series of command sequences ). When you run this script file, the command sequence contained in the file will be executed.

HelloWorld

The first line of the Shell script must be in the following format :#! /Bin/bash

Symbol #! Specifies the parsing program of the script file. In this example, bash or other shells are used. For example #! /Bin/sh.

After the script is edited, it must have executable attributes. Chmod + x filename

Shell script hello. sh

View plaincopy to clipboardprint?
#! /Bin/bash
Echo "hello world! "
Mkdir./helloworld
#! /Bin/bash
Echo "hello world! "
Mkdir./helloworld

Variables in Shell

In Shell programming, all variables are composed of strings and do not need to be declared in advance.

Shell script s1.sh

View plaincopy to clipboardprint?
#! /Bin/sh
# Comments
# Set variable
A = "hello"
# Print
Echo "A is: $"
#! /Bin/sh
# Comments
# Set variable
A = "hello"
# Print
Echo "A is: $"

PASS command line parameters

$ #: Number of command line parameters for input scripts

$ *: All command line parameters with spaces between parameter values

$0: Command itself (shell file name)

$1: The First Command Line Parameter

$2: The second command line parameter

Shell script s2.sh

View plaincopy to clipboardprint?
#! /Bin/sh
Echo "numer of vars:" $ #
Echo "values of vars:" $ *
Echo "value of var1:" $1
Echo "value of var2:" $2
Echo "value of var3:" $3
Echo "value of var4:" $4
#! /Bin/sh
Echo "numer of vars:" $ #
Echo "values of vars:" $ *
Echo "value of var1:" $1
Echo "value of var2:" $2
Echo "value of var3:" $3
Echo "value of var4:" $4

Run./s2.sh a B c d

Output result:

Numer of vars: 4
Values of vars: a B c d
Value of var1:
Value of var2: B

Value of var3: c

Value of var4: d

Local variables in Shell

Shell script s3.sh

View plaincopy to clipboardprint?
#! /Bin/bash
Hello = "var1"
Echo $ hello
Function funcl
{
Local hello = "var2"
Echo $ hello
}
Funcl
Echo $ hello
#! /Bin/bash
Hello = "var1"
Echo $ hello
Function funcl
{
Local hello = "var2"
Echo $ hello
}
Funcl
Echo $ hello

When a variable is assigned a value for the first time, the local keyword can be added to declare a local variable.

Note: (1) When a variable is assigned a value, there cannot be spaces between the left and right sides of "= ".

(2) The end of a BASH statement does not require a semicolon

Control Structure in Shell

If statement

If [expression]

Then

# Code block

If

If [expression]

Then

# Code block

Else

# Code block

Fi

Comparison Operators

Comparison operation Integer Operation string operation comparison operation Integer Operation string operation
Same-eq = greater than or equal to-ge
Different-ne! = Less than or equal to-le
Greater than-gt> null-z
Less than-lt <not empty-n


Instance used:

Compare whether integer a is greater than integer B: if [$ a-gt $ B] to judge whether string a is null: if [-z $ a]

Note:

(1) left and right sides of the "[" and "]" symbols are left with spaces (2) "=" Left and Right contain spaces

Shell script s4.sh

View plaincopy to clipboardprint?
#! /Bin/bash
A = $1
B = $2
If [-z $ a] | [-z $ B]
Then
Echo "please enter 2 no"
Exit 1
Fi
If [$ a-eq $ B]; then
Echo "number a = number B"
Else if [$ a-gt $ B]
Then
Echo "number a> number B"
Elif [$ a-lt $ B]
Then
Echo "number a <number B"
Fi
Fi
#! /Bin/bash
A = $1
B = $2
If [-z $ a] | [-z $ B]
Then
Echo "please enter 2 no"
Exit 1
Fi
If [$ a-eq $ B]; then
Echo "number a = number B"
Else if [$ a-gt $ B]
Then
Echo "number a> number B"
Elif [$ a-lt $ B]
Then
Echo "number a <number B"
Fi
Fi

Judgment

-E file already exists-f file is a common file-s file size is not zero-d file is a directory

-The r file can read the-w file for the current user and write the-x file to the current user.

Shell script s5.sh

View plaincopy to clipboardprint?
#! /Bin/sh
Folder =/home
[-R "$ folder"] & echo "Can read $ folder"
[-F "$ folder"] | echo "this is not file"
#! /Bin/sh
Folder =/home
[-R "$ folder"] & echo "Can read $ folder"
[-F "$ folder"] | echo "this is not file"

Shell script s6.sh

View plaincopy to clipboardprint?
#! /Bin/bash
DIR = $1
# If the string empty
If ["$ DIR" = ""]
Then
Echo "usage: 'basename $ 0' directory to create"> & 2
Exit 1
Fi
Echo "dir" $ DIR
If [-d $ DIR]
Then
Echo "The directory already exist"
Exit 0
Else
Echo "The directory does exist"
Echo-n "Create is now? [Y/N]:"
Read create
If ["$ create" = "y"] | ["$ create" = "Y"]
Then
Echo "creating now"
If [mkdir $ DIR]
DIR = ""
Fi

If ["$ DIR" = ""]
Then
Echo "create directory sucess"
Else
Echo "create directory error"
Fi
Elif ["$ create" = "n"] | ["$ create" = "N"]
Then
Echo "does not create directory"
Exit 0
Else
Echo "Errors order"
Exit 1
Fi
Fi
#! /Bin/bash
DIR = $1
# If the string empty
If ["$ DIR" = ""]
Then
Echo "usage: 'basename $ 0' directory to create"> & 2
Exit 1
Fi
Echo "dir" $ DIR
If [-d $ DIR]
Then
Echo "The directory already exist"
Exit 0
Else
Echo "The directory does exist"
Echo-n "Create is now? [Y/N]:"
Read create
If ["$ create" = "y"] | ["$ create" = "Y"]
Then
Echo "creating now"
If [mkdir $ DIR]
DIR = ""
Fi

If ["$ DIR" = ""]
Then
Echo "create directory sucess"
Else
Echo "create directory error"
Fi
Elif ["$ create" = "n"] | ["$ create" = "N"]
Then
Echo "does not create directory"
Exit 0
Else
Echo "Errors order"
Exit 1
Fi
Fi

For Loop

The for loop structure is different from the C language. In bash, the basic structure of the for Loop

For var in [list]

Do

# Code lock

Done

$ Var is the cyclic control variable, and [list] is a set of var traversal. The do/done pair contains the cyclic body.

In addition, if for and do are written in the same line, you must add ";" before do ";".

Shell script s7.sh

View plaincopy to clipboardprint?
#! /Bin/bash
For day in Sun Mon Tue Wed Thu Fri Sat
Do
Echo $ day
Done
#! /Bin/bash
For day in Sun Mon Tue Wed Thu Fri Sat
Do
Echo $ day
Done

Shell scripts count the number of files in the current directory

View plaincopy to clipboardprint?
#! /Bin/bash

Counter = 0
For files in *
Do
Counter = 'expr $ counter + 1'
Done
Echo "There are $ counter files in 'pwd' we need to process"
#! /Bin/bash

Counter = 0
For files in *
Do
Counter = 'expr $ counter + 1'
Done
Echo "There are $ counter files in 'pwd' we need to process"

Shell scripts output user-input numbers in reverse order

View plaincopy to clipboardprint?
#! /Bin/bash
Echo-n "Pleasw enter number :"
Read n
Sd = 0
Rev = ""
On = $ n
Echo "$ n"
While [$ n-gt 0]
Do
Sd = $ ($ n % 10) # get Remainder
N = $ ($ n/10) # get next digit
Rev = $ (echo $ rev $ sd)
Done
Echo "$ on in a reverse order $ rev"
#! /Bin/bash
Echo-n "Pleasw enter number :"
Read n
Sd = 0
Rev = ""
On = $ n
Echo "$ n"
While [$ n-gt 0]
Do
Sd = $ ($ n % 10) # get Remainder
N = $ ($ n/10) # get next digit
Rev = $ (echo $ rev $ sd)
Done
Echo "$ on in a reverse order $ rev"

Until Loop

Basic Structure of the until Loop

Until [condition]

Do

# Code block

Done

The difference between while and until is that when while is true, until is false.

Shell scripts move a file. If the target exists, the file is monitored until the file is deleted.

View plaincopy to clipboardprint?
#! /Bin/bash
If ["$1" = ""] | ["$2" = ""]
Then
Echo "Please enter file name"
Exit 1
Fi
If [-e $2]
Then
Echo "The file already exists"
Until [! -F $2]
Do
Sleep 1
Done
Fi
If [! 'Mv $1 $ 2']
Then
Echo "mv sucessful"
Else
Echo "mv error"
Fi
#! /Bin/bash
If ["$1" = ""] | ["$2" = ""]
Then
Echo "Please enter file name"
Exit 1
Fi
If [-e $2]
Then
Echo "The file already exists"
Until [! -F $2]
Do
Sleep 1
Done
Fi
If [! 'Mv $1 $ 2']
Then
Echo "mv sucessful"
Else
Echo "mv error"
Fi


Case statement

Case statement Structure

Case "$ var" in

Condition1)

;;

Condion2)

;;

*)

Default statments ;;

Esac

Shell script determines the case sensitivity of keyboard input

View plaincopy to clipboardprint?
#! /Bin/bash
Echo "Hit a key, then hit return ."
Read Keypress
Case "$ Keypress" in
[A-Z]) echo "Uppercase letter ";;
[A-z]) echo "Lowercase letter ";;
[0-9]) echo "Digit ";;
*) Echo "Punctuation, whitespace, or other ";;
Esac
#! /Bin/bash
Echo "Hit a key, then hit return ."
Read Keypress
Case "$ Keypress" in
[A-Z]) echo "Uppercase letter ";;
[A-z]) echo "Lowercase letter ";;
[0-9]) echo "Digit ";;
*) Echo "Punctuation, whitespace, or other ";;
Esac

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.