The first lesson of shell script learning

Source: Internet
Author: User
Tags arithmetic arithmetic operators bit set echo command logical operators

The shell is a programming language and a service that accesses the operating system kernel.

The types of shell that are common to Linux are:

Bourne Shell (/usr/bin/sh or/bin/sh)

Bourne Again Shell (/bin/bash)

C Shell (/USR/BIN/CSH)

K Shell (/usr/bin/ksh)

Shell for Root (/sbin/sh)

Two ways to execute a shell script

./shell.sh executes according to the shell specified in the first line of the shell script

/bin/sh Test.sh executes according to the shell specified in the command line

/bin/php test.php

Shell variables

Define variable: your_name= "runoob.com" for file in ' ls/etc '

Use variable: Echo $your _name echo ${your_name} echo "I am good at ${skill}script"

Delete variable: unset variable_name

Variable type

1) Local Variables

2) Environment variables

3) Shell variables

Shell string

Single quote: Str= ' This is a string '

Double quotes:

Your_name= ' QINJX '
Str= "Hello, I know your is \" $your _name\ "! \ n "

Stitching strings:

Your_name= "QINJX"
greeting= "Hello," $your _name "!"
greeting_1= "Hello, ${your_name}!"
echo $greeting $greeting _1

Get string Length:

string= "ABCD"
echo ${#string} #输出 4

To extract substrings:

String= "Runoob is a great site"
echo ${string:1:4} # Output Unoo

To find a substring:

String= "Runoob is a great company"
echo ' expr index ' $string ' is ' # output 8

Shell Array

Bash supports one-dimensional arrays, does not support multidimensional arrays, and does not limit the size of arrays

Define array:: Array name = (value 1 value 2 ...) Value N) array_name= (value0 value1 value2 value3)

or ARRAY_NAME[0]=VALUE0

Array_name[1]=value1
Array_name[n]=valuen

Read array: ${array name [subscript]} Valuen=${array_name[n]}

Use the @ symbol to get all the elements of the array: Echo ${array_name[@]}

Gets the length of the array:

# Gets the number of array elements
length=${#array_name [@]}
# or
length=${#array_name [*]}
# Gets the length of an array of individual elements
lengthn=${#array_name [n]}

Shell Pass Parameters

When we execute a shell script, we pass parameters to the script, and the format of the parameters obtained in the script is: $n. n represents a number, 1 is the first argument to execute the script, 2 is the second argument to execute the script, and so on.

Example:

#! /bin/bash

echo "Shell pass parameter instance! ";

echo "Executed the file name: $";

echo "The first parameter is: $ zero";

echo "The second parameter is: $";

echo "The third parameter is: $ $";

Execution results

./test.sh 1 2 3

Shell Pass argument instance!

File name executed:./test.sh

The first parameter is: 1

The second parameter is: 2

The third parameter is: 3

In addition, several special characters are used to handle parameters

Parameter description Description
$# The number of arguments passed to the script
$*

Displays all parameters passed to the script in a single character.

If "$*" is enclosed in ["], output all parameters in the form of" $ $ ".

$$ The current process ID number for the script to run
$! ID number of the last process running in the background
[Email protected]

Same as $*, but quoted when used, and returns each parameter in quotation marks.

such as "[email protected]" in the case of ["], with" $ "" $ "" $ "..." $n "to output all parameters

$- Displays the current options used by the shell, same as the SET command function
$? Displays the exit status of the last command. 0 means there is no error, and any other value indicates an error.

Example:

#!/bin/bash

echo "Shell pass parameter instance! ";

echo "The first parameter is: $ zero";

echo "Number of parameters: $#";

echo "The number of arguments passed as a string display: $*";

Execute the script with the following results:

./test.sh 1 2 3

Shell Pass argument instance!

The first parameter is: 1

Number of parameters: 3

The number of arguments passed is displayed as a string: 1 2 3

The difference between $* and [email protected]

Same point: All parameters are referenced

Different points: only in quotation marks. Assuming that the script was written with the parameters 1, 2, 3, then "*" is equivalent to "1 2 3" (passing a parameter), and "@" is equivalent to "1" "2" "3" (three parameters passed).

#!/bin/bash

echo "-\$* Demo"

For i in "$*";d o

Echo $i

Done

echo "--\[email protected] Demo"

For i in "[email protected]";d o

Echo $i

Done

Execute the script with the result as shown below

./test.sh 1 2 3

--$* Demo--

1 2 3

[Email protected] Demo--

1

2

3

Shell Array

The shell array is represented by parentheses, and the elements are separated by a "space" symbol.

Shell operators

Expr is an expression evaluation tool that uses it to perform evaluation operations on expressions.

Val= ' Expr 2 + 2 ';

echo "The sum of two numbers: $val";

Two note: There is a space between the expression and the operator, for example, it is not correct and must be written in 2 + 2, which is not the same as most of the programming languages we are familiar with.

The complete expression is to be contained, note that this character is not a common single quote, below the ESC key.

Arithmetic operators

Operator Description Example
+ Addition ' Expr $a + $b ' result is 30
- Subtraction ' Expr $a-$b ' result is-10
* Multiplication ' Expr $a \* $b ' result is 200
/ Division ' Expr $b/$a ' result is 2
% Take surplus ' Expr $b% $a ' result is 0
= Assign value A= $b will assign the value of variable B to a.
== Equal. Used to compare two numbers, the same returns true. [$a = = $b] returns false
!= Not equal. Used to compare two numbers, and returns true if they are different. [$a! = $b] returns to True

Relational operators

Relational operators only support numbers, and strings are not supported unless the value of the string is a number

Operator Description Example
-eq Detects whether two numbers are equal and returns true for equality [$a-eq $b] returns false
-ne Detects whether two numbers are equal and returns true if they are not equal [$a-NQ $b] returns True
-gt Detects if the number on the left is greater than the right and, if it is, returns true [$a-gt $b] returns false
-lt Detects if the left number is less than the right, and returns true if it is [$a-lt $b] returns True
-ge Detects if the left number is greater than or equal to the right, and returns true if it is [$a-QE $b] returns false
-le Detects if the left number is less than or equal to the right, and returns true if it is [$a-le $b] returns True

Boolean operator

Operator Description Example
! Non-arithmetic, expression true returns false, otherwise true [!false] Returns True
-O Or operation, an expression of true is true [$a-lt 20-o $b-GT 100] Returns True
-A With arithmetic, two expressions are true to return true [$a-lt 20-a $b-GT 100] returns false

logical operators

Operator Description Example
&& Logic and [[$a-lt && $b-GT 100]] returns false
|| Logical OR OR [[$a-lt | | $b-GT 100]] returns True

string Operators

A= "abc" b= "EFG"

Operator Description Example
= Detects whether a string is equal and returns true for equality [$a = $b] returns false
!= Detects whether two strings are equal, not equal returns True [$a! = $b] Returns True
-Z Detects whether the string length is 0 and returns true for 0 [-Z $a] returns false
-N Detects whether the string length is 0 and does not return true for 0 [-N $a] returns true
Str Detects if the string is empty and does not return true for null [$a] returns True

File Test Operators

The variable file represents the document "/var/www/runoob/test.sh", which is 100 bytes in size and has RW permissions. The following code detects the properties of the file.

Operator Description Example
-B File Detects if the file is a block device file, and returns True if it is [-B $file] returns false
-C file Detects if the file is a character device file, and returns True if it is [-C $file] returns false
-D File Detects if the file is a directory, and returns True if it is [-D $file] returns false
-F File Detects if the file is a normal file (neither a directory nor a device file), and if so, returns True [-F $file] returns True
-G file Detects if the file has a sgid bit set, and returns True if it is. [-G $file] returns false
-K File Detects if the file has a sticky bit set (sticky bit), and returns True if it is [-K $file] returns false
-P File Detects if the file is a well-known pipe, and if so, returns True [-P $file] returns false
-U file Detects if the file has a suid bit set, and returns True if it is [-U $file] returns false
-R File Detects if the file is readable and returns true if it is [-R $file] returns true
-W File Detects if the file is writable and returns true if it is [-W $file] returns True
-X File Detects if the file is executable and returns true if it is [-X $file] returns True
-S file Detects whether the file is empty (file size is 0), NOT NULL returns True [-S $file] returns True
-E File Detects whether the file (including the directory) exists and, if so, returns True [-e $file] returns True

Shell echo Command

1. Display normal string

echo "It is a test"

The double quotes here are completely omitted, and the following commands are identical to the previous instance:

Echo It is a test

2. Show escape characters

echo "\" It is a test\ ""

The result will be

"It is a test"

3. Display variables

#!/bin/bash

Read name

echo "$name It is a test"

Name receives a variable of standard revenue, the result will be:

SH test.sh

OK #标准输入

OK It is a test #输出

4. Show line break

Echo-e "ok! \ n "#-e Open escape

echo "It is a test"

Output results

Ok!

It is a test

5. Show No Line break

#!/bin/bash

Echo-e "ok! \c "#-e Open escape \c No Line break

echo "It is a test"

Output results

Ok! It is a test

6. Display results directed to file

echo "It is a test" > myfile

7. Output a string as is, without escaping or taking a variable (in single quotes)

echo ' $name \ '

Output results

$name \ "

8. Show command Execution results

Echo ' Date '

The result will show the current date

Mon Dec 18:33:04 UTC 2016

The first lesson of shell script learning

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.