Home PC Games Linux Windows Database Network Programming Server Mobile  
           
  Home \ Linux \ Shell Scripting Basics     - Linux command -nohup & (Linux)

- Java gets the current system time System.currentTimeMillis () (Programming)

- 25 Git Usage Tips (Linux)

- Using iptables achieve NAT (Linux)

- Simple to use multi-threaded programming under Linux mutex and condition variable (Programming)

- Defensive programming in PHP (Programming)

- Elementary OS Freya global menu (Linux)

- Android Service service applications and the phone SMS Listener Listener (Programming)

- Quickly locate the mistakes by gdb location (Programming)

- SSH keys using login and password to log prohibited practice (Linux)

- Ubuntu security settings and tools (Linux)

- Spring next ActiveMQ combat (Programming)

- Linux variable learning experience (Linux)

- Python uses multi-process pool (Programming)

- Java collections series (Programming)

- To build PHP environment (Nginx + MariaDB + PHP7) under CentOS 6.5 (Server)

- Orionode source Linux Mint installation (Linux)

- 10 Regulation of painless SQL Schema (Database)

- CentOS 6 / Linux su: Unable to set user ID: Resource temporarily unavailable (Linux)

- Ubuntu 15.04 install Complete Guide (Linux)

 
         
  Shell Scripting Basics
     
  Add Date : 2017-01-08      
         
         
         
  On Unix / Linux common Shell script interpreter have bash, sh, csh, ksh, etc., they are customarily referred to as a Shell. We often say how many of Shell, in fact, that the Shell script interpreter.

Several common Shell

** Sh **
sh developed by Steve Bourne, Bourne shell is an abbreviation, is the standard Unix sh default shell.
** Bash **
bash is jointly done by Brian Fox and Chet Ramey. Bourne Again Shell is an abbreviation. linux bash is the standard default shell.
** Ash **
ash was written by Kenneth Almquist, linux in a small footprint with minimal shell, it contains 24 internal command, which is not very convenient to use.
** Csh **
csh is relatively large in the linux kernel, which consists to William Joy, represented by a total of 47 authors compiled a total of 52 internal command. The shell is actually pointing to / bin / tcsh such a shell, that is to say csh tcsh.
** Ksh **
ksh is written by Eric Gisin, Korn Shell is an abbreviation for a total of 42 internal command. The biggest advantage of this shell is almost ksh and commercial release is fully compatible. So you can try a commercial version of the performance at no cost to purchase the commercial version of the situation.

** Note: bash linux is the default shell, which is based on Bourne Shell, absorbing some of the features of csh and ksh, bash is fully compatible with sh, that is to say, with sh wrote the script without modification executed in bash **
The first script Shll

$ Vi hello.sh # Create a shell script (a file with the extension sh, sh on behalf of shell, the extension does not affect the execution of the script. You can also directly named hello)
Enter the following code in the script:

#! / Bin / bash # "#!" Is a convention tag that tells the system which requires the use of Shell.
echo "Hello World!"
Run Shell method:

$ Chmod + x hello.sh # added to the file execute permission
$ ./hello.sh # Script execution

$ / Bin / sh hello.sh # sh to run the script
$ / Bin / bash hello.sh # bash to run the script
Example:
Write a script that reads the name from standard input (stdin), standard output (stdout) on.

# / Bin / bash

echo "What's your name?"
read NAME
echo "Hello $ {NAME}"
Shell Variables

Define the variable
The variable name and equal sign directly can not have spaces. Variable naming rules out need to follow the following rules:
1, the first character must be a letter (a-z, A-Z)
2, no spaces, use an underscore (_)
3, can not use punctuation
4, can not use the shell keywords (use help at the command line, you can view the reserved keyword)

Variable definitions Example:

variableName = "value"
Using Variables
Use a defined variable, just in front of the variable name $ symbol on it. Such as:

variableName = "value"
echo $ variableName
Sometimes the need braces variable name outside help explain the identification variable boundary, as in the following case

SKILL = Ada
echo "I'm a good at $ {SKILL} Script"
Redefine variables
Variable is defined and can be re-defined, such as:

#! / Bin / bash
NAME = Dave
echo "Hello $ {NAME}"

NAME = Abby
echo "Hello $ {NAME}"
Read-only variables
Use the command readonly variables can be defined as read-only variable, the value of read-only variables can not be changed

#! / Bin / bash
NAME = Dave
readonly NAME
NAME = Abby
Run the script error, the following results

./test.sh: line 5: NAME: readonly variable
Remove variable
Use the unset command to delete a variable, the variable can not be used again after being deleted; unset command can not remove the read-only variable
Example:

#! / Bin / bash
NAME = Dave
unset NAME
echo $ NAME
Operating results will not have any output.

Shell special variables

Examples

#! / Bin / bash

echo "File Name: $ 0"
echo "First Parameter: $ 1"
echo "Second Parameter: $ 2"
echo "All Parameter: $ @"
echo "All Parameter: $ *"
echo "Total Number of Parameter $ #"
echo "The Shell of the process ID is: $$"
The result:

$ ./test.sh Dave Abby
File Name: ./test.sh
First Parameter: Dave
Second Parameter: Abby
All Parameter: Dave Abby
All Parameter: Dave Abby
Total Number of Parameter 2
The Shell of the process ID is: 2752
$ Echo $? # See ./test.sh exit status. Under normal circumstances the successful return 0, failed -1
0
* $ * And $ @ * distinction
A lot of books written on the shell when they are double quotes, will be $ * All arguments as a whole, $ @ will each parameter separately. However, I did not find such a situation when running the script. I was testing in Ubuntu1204 version. Code is as follows

#! / Bin / bash


echo '$ * =' "$ *"
echo '$ @ =' "$ @"
Shell replacement

Command substitution
Command substitution refers to the shell command can be executed, the output will be temporarily stored in an appropriate place output
Example:

#! / Bin / bash

DATE = `date`
echo "$ DATE"

Variable substitution


Example:

#! / Bin / bash

echo $ {var: - "Hello"}
echo $ var

echo $ {var: = "Hello"}
echo $ var

echo $ {var: + "World"}
echo $ var

unset var
echo $ {var:? "message"}
echo $ var
The results are as follows:

$ ./test.sh
Hello

Hello
Hello
World
Hello
./test.sh: line 13: var: message
Shell if statement

if true and false statements by relational operators determine expression to determine the execution of that branch, Shell has three if statements.

if ... fi statement
if ... else ... fi statement
if ... elif ... else ... fi statement
Syntax if ... fi statement

if [expression]
then
    Statement (s) to be executed if expression is true
fi
** Note: You must have a space between the ** expression and brackets. Otherwise there will be a syntax error
Example:

#! / Bin / bash

a = 10
b = 20

if [$ a == $ b]
then
        echo "a == b"
fi

if [$ a! = $ b]
then
        echo "a! = b"
fi
if ... else ... fi statement syntax

if [expression]
then
    Statement (s) to be executed if expression is true
else
    Statement (s) to be executed if expression is not true
fi
Example:

#! / Bin / bash

a = 10
b = 20

if [$ a == $ b]
then
        echo "a == b"
else
        echo "a! = b"
fi
if ... elif ... fi statement syntax

if [expression 1]
then
    Statement (s) to be executed if expression 1 is true
elif [expression 2]
then
    Statement (s) to be executed if expression 2 is true
elif [expression 3]
then
    Statement (s) to be executed if expression 3 is true
else
    Statements to be executed if expression not is true
fi
Example:

#! / Bin / bash

a = 10
b = 20

if [$ a == $ b]
then
        echo "a == b"
elif [$ a -gt $ b]
then
        echo "a> b"
elif [$ a -lt $ b]
then
        echo "a else
        echo "None of the condition met"
fi
Shell operators

bash supports many operators. Including arithmetic operators, relational operators, Boolean operators, string operators and file test operators.

Arithmetic operators

bash implemented in math syntax.
- Use the expr expression evaluation tool. expr 1 + 2
- [1 + 2] - ((1 + 2))
When you use expr to note:
- There must be a space between expressions and operators.
- The complete expression to be "contained up.

Example:

#! / Bin / bash

a = 10
b = 20

echo "` expr $ a + $ b` "
echo $ [$ a + $ b]
echo $ ((a + b))
echo "` expr $ a - $ b` "
echo "` expr $ a \ * $ b` "# * No need to escape
echo $ [$ a * $ b]
echo "` expr $ a / $ b` "
echo "` expr $ a% $ b` "

Relational Operators


Relational operators only support digital, it does not support the string. Unless the value of the string is a number.
Example:

#! / Bin / bash

a = 10
b = 20

if [$ a -eq $ b]
then
        echo "a == b"
else
        echo "a! = b"
fi

if [$ a -ne $ b]
then
        echo "a! = b"
else
        echo "a == b"
fi

if [$ a -gt $ b]
then
        echo "a> b"
else
        echo "a fi

if [$ a -lt $ b]
then
        echo "a else
        echo "a> b"
fi

if [$ a -ge $ b]; then echo "a> b"; else echo "a if [$ a -le $ b]; then echo "a b"; fi

Boolean operators

Example:

#! / Bin / bash

a = 10
b = 20

if [$ a -eq $ b!]; then echo "a == b"; else echo "! a = b"; fi

if [$ a -lt $ b -o $ b -gt $ a]; then echo "a b"; fi

if [$ a -le $ b -a $ b -ge $ a]; then echo "a b"; fi

String Operators

Example:

#! / Bin / bash

a = "abc"
b = "edf"

if [! $ a = $ b]; then echo "! a = b"; else echo "a == b"; fi

if [! $ a = $ b]; then echo "! a = b"; else echo "a == b"; fi

if [-z $ a -o -z $ b]; then echo "string length is not zero";
        else echo "string length is zero"; fi

if [-n $ a -a -n $ b]; then echo "string length is zero"
        else echo "string length is not zero"; fi

if [$ a -a $ b]; then echo "string length is zero"
        else echo "string length is not zero"; fi
File Test Operators
File test operator is used to detect various attributes of the file
Example:

#! / Bin / bash



if [-b $ 1]; then echo "$ 1 is block file"; else echo "$ 1 is not block file"; fi

if [-c $ 1]; then echo "$ 1 is str file"; else echo "$ 1 is not str file"; fi

if [-d $ 1]; then echo "$ 1 is directory file"; else echo "$ 1 is not directory file"; fi

if [-f $ 1]; then echo "$ 1 is ordinary file"; else echo "$ 1 is not ordinary file"; fi

if [-g $ 1]; then echo "$ 1 SGID bit"; else echo "$ 1 not SGID bit"; fi

if [-k $ 1]; then echo "$ 1 Sticky bit"; else echo "$ 1 not Sticky not bit"; fi

if [-p $ 1]; then echo "$ 1 is pipe file"; else echo "$ 1 is not pipe file"; fi

if [-u $ 1]; then echo "$ 1 SUID bit"; else echo "$ 1 not SUID bit"; fi

if [-r $ 1]; then echo "$ 1 is read file"; else echo "$ 1 is not read file"; fi

if [-w $ 1]; then echo "$ 1 is write file"; else echo "$ 1 is not write file"; fi

if [-x $ 1]; then echo "$ 1 is execute file"; else echo "$ 1 is not execute file"; fi

if [-s $ 1]; then echo "$ 1 is not zero"; else echo "$ 1 is zero"; fi

if [-e $ 1]; then echo "$ 1 exists"; else echo "$ 1 not exists"; fi

The result:

$ ./test.sh Test.sh
test.sh is not block file
test.sh is not str file
test.sh is not directory file
test.sh is ordinary file
test.sh not SGID bit
test.sh not Sticky not bit
test.sh is not pipe file
test.sh not SUID bit
test.sh is read file
test.sh is write file
test.sh is execute file
test.sh is not zero
test.sh exists

Shell string

Shell string enclosed in double quotes can be single quotes, or may not be in quotation marks. Such as:

#! / Bin / bash

a = "abc"
b = edf
c = 'hij'

echo $ a
echo $ b
echo $ c
The difference between double quotes and single quotes
Single quote: Any characters in single quotation marks are output as single quotes in the variable is invalid. Single quote can not appear in a single quote.
Double quotes: double quotes can be variable, double quotes can appear escape character.
Example:

#! / Bin / bash

a = "abc"
b = edf

echo "$ a"
echo '$ b'
Results are as follows:

$ ./test1.sh
abc
$ B
Several uses strings

#! / Bin / bash

a = "abc"
b = edf

echo "$ a" $ b ""

** #### ** Spliced output string is abcedf
#! / Bin / bash

a = "abc"

echo $ {# a}

#### ** ** Gets the length of the string
#! / Bin / bash

a = "abc"

echo $ {a: 1: 2}

** #### ** Extract strings enter the result is bc

#! / Bin / bash

a = "hello world"

echo `expr index" $ a "d` ## character d in the string to find the first occurrence of $ a seat

** #### ** Find character or string
Shell arrays

Define arrays
bash supports one-dimensional array (does not support multidimensional arrays), and does not define the size of the array. Subscript array elements are numbered starting from zero, to obtain elements in the array to make use of the subscript, subscript leapfrog integer or arithmetic expression whose value should be greater than or equal to 0.

The definition of an array There are three ways

array_name = ( "hello" "world") # each element separated by a space directly
array_name = (
hello
world) # spaced elements directly newline
c [0] = hello
Each element c [2] = world # array of individually defined
Read format array
The general format is read array element value:

 $ {Array_name [index]}
Example:

#! / Bin / bash

a = ( "hello" "world")
b = (
hello
world)
c [0] = hello
c [2] = world
echo "$ {a [0]} $ {a [1]}"
echo "$ {b [0]} $ {b [1]}"
echo "$ {c [0]} $ {c [2]}"
echo "$ {a [@]}" # @ made on behalf of all the elements in the array
echo "$ {b [*]}" # * made on behalf of all the elements in the array
echo "$ {# a [@]}" # Get the number of elements in the array
echo "$ {# a [0]}" # get the length of a single element of the array
Shell's branch statement

case ... esac statement is a branch of the shell, a value or a pattern match. If the match is successful, execute commands matching, case statement format is as follows:

value in case
Mode 1)
    command1
    command2
    command3
    ;;
Mode 2)
    command1
    command2
    command3
    ;;
*)
    command1
    command2
    command3
    ;;
esac
case work as shown above. The value must be behind the keyword in, each model must end with a closing parenthesis. The value can be variable or constant. After matching a pattern consistent with values found, during which all commands executed until ;;. (;; C-like language break)
The value of each of the detected matching patterns, once the pattern matching, the pattern matching after executing the corresponding content is no longer continue with other modes. If there is no matching a pattern, use * to capture that value. In the implementation of the corresponding content.

Example:

#! / Bin / bash

case $ 1 in
-f)
        echo "FILE"
        ;;
-d)
        echo "DIR"
        ;;
*)
        echo "NONE"
        ;;
esac

The result:

$ ./test.sh -f
FILE
$ ./test.sh -d
DIR
$ ./test.sh
NONE
$ ./test.sh -g
NONE
Shell cycle

Shell in the for loop
The general format of the for loop

for variable in list
do
    command1
    command2
    .....
done
List is a set of values (arrays, strings, etc.) consisting of a sequence, each value separated by a space. Each time through the loop, it will be next on the list a value is assigned to variable.

#! / Bin / bash

for loop in `date`
do
        echo $ loop
done
The result:

$ ./test.sh
six
May
2
22:32:38
HKT
2015
Shell in while loop
while loop format

while command
do
    Statement (s) to be executed if command is true
done
## Command ships for the test conditions, when the conditions are really executed
Example:

#! / Bin / bash

while read VALUE
do
        echo $ VALUE
done
## Reads a string from the standard input
Shell in circulation until
Format until the cycle is as follows:

until command
do
    Statement (s) to be executed if command is false
done
command is usually conditional expression, if the return value is false, then continue the loop, otherwise out of the loop.
Example:

#! / Bin / bash

a = 0

until [! $ a -lt 10]
do
        echo $ a
        a = $ [$ a + 1]
done

# Output 0-9
You can use the keyword loop break out of the loop and continue keywords, such as the use of C programs break and continue

The Shell function

Definition Format Shell function is as follows:

function function_name () {
    list of commands
    [Return value]
}

## Keyword function can be omitted.
## Function return value can only be an integer, generally used to indicate whether the function is executed successfully.
## If not return statement, the last command will be run as a result of the return value.
Use $ ##? Receive function return values
Function parameters:
When you call a function that can be passed parameters. In the body of the function inside. By like to get the value of the parameter n (and to get the script as a parameter). When the value of n is greater than or equal to 10, the need to increase the parameters get braces, such as {11}.

Function call:
Call the function only need to give the function name. It does not require parentheses.
If you want to call the function directly from the terminal function is defined in the main directory .profile files can be in. So every time after landing, at the command prompt, enter the name of the function can be called directly
You can use the unset command to delete function

unset .f function_name # .f must add parameters before the function name
Example:

#! / Bin / bash

fun () {
        echo $ 1
        echo $ 2
        return $ (($ 1 + $ 2))

}

fun $ 1 $ 2 # call the function, passing parameters, where $ 1 and $ 2 is a shell script parameters
ret = $? # receiver function return value
echo "The sum of two numbers is $ ret"
The result:

 ./test1.sh 10 20
10
20
The sum of two numbers is 30
Shell file contains

shll content can be external script into the current script
shell script format contained

. Filename
or

source filename
Note: The script does not need execute permissions are included also be performed.
Example:

#! / Bin / bash

. ./test1.sh $ 1 $ 2

echo test1.sh run over
Results of the:

$ Ll test1.sh
-rw-rw-r-- 1 gino gino 121 5 Yue 2 23:46 test1.sh
$ Cat test1.sh
#! / Bin / bash

fun () {
    echo $ 1
    echo $ 2
    return $ (($ 1 + $ 2))

}

fun $ 1 $ 2
ret = $?
echo "The sum of two numbers is $ ret"


$ ./test2.sh 1 2
1
2
The sum of two numbers is 3
test1.sh run
     
         
         
         
  More:      
 
- tar decompression problems gzip: stdin: not in gzip format (Linux)
- Swift string common method (Programming)
- Linux Mint 17 set up the Ruby environment (Linux)
- Linux memory management (Linux)
- linux remote control software (Linux)
- Android will save the picture to see the album and timely (Programming)
- C ++ inheritance and derived (induction principle) (Programming)
- Standardized UNIX command-line tool (Linux)
- How to configure security services under Linux (Linux)
- Implement firewall function on a closed Linux machine (Linux)
- Enterprise-class GitHub warehousing environment build (Server)
- Fedora 23 How to install LAMP server (Server)
- Thinking in Java study notes - Generics (Programming)
- Open container cluster management system architecture and components introduced Kubernetes (Server)
- Prevent security threats caused Rootkit (Linux)
- bash login and welcome message: / etc / issue, / etc / motd (Linux)
- Ubuntu iptables prevent IP attacks (Linux)
- MySQL full-index scan bug (Database)
- Ubuntu 15.10 installation and deployment Swift development environment (Linux)
- How to use Android Studio to play more package names APK (Programming)
     
           
     
  CopyRight 2002-2022 newfreesoft.com, All Rights Reserved.