An introductory tutorial on shell command usage in Linux

Source: Internet
Author: User
Tags arithmetic arrays case statement data structures error code logical operators numeric value posix

When to use the shell

Because the shell appears to be a common feature between UNIX systems, and has been standardized by POSIX. As a result, the shell script can be applied to many systems as long as it is written "attentively". Therefore, the reason to use shell scripts is based on:

Simplicity: The shell is a high-level language through which you can express complex operations succinctly.
Portability: Using the functionality defined by POSIX, scripts can be executed on different systems without modification.
Easy to develop: a powerful and Hsueh script can be completed in a short period of time.


However, given the command restrictions and efficiency issues with the shell script, the following situations do not typically use the shell:

resource-intensive tasks, especially when you need to consider efficiencies (e.g., sorting, hashing, and so on).
Mathematical operations that need to handle large tasks, especially floating-point operations, precise operations, or complex arithmetic operations (which are typically handled using C + + or FORTRAN).
There is a cross-platform (operating system) porting requirement (typically using C or Java).
Complex applications, when you must use structured programming (type checking of variables, function prototypes, and so on).
For critical task applications that affect the overall system.
Tasks that are highly demanding for security, such as the need for a robust system to prevent intrusion, cracking, malicious destruction, and so on.
A project consists of various parts of a chain of dependencies.
Large file operations are required.
Requires support for multidimensional arrays.
Data structures need to be supported, such as lists or numbers.
GUI for graphical interfaces needs to be generated or manipulated.
Requires direct operating system hardware.
An I/O or socket interface is required.
Interfaces that require the use of libraries or legacy old code.
Private, closed-source applications (the shell script puts the code in a text file that the world can see).


If your application matches any of the above, consider a more powerful language--perhaps Perl, Tcl, Python, ruby--, or a higher-level compiled language such as C + +, or Java. Even so, you'll find that using a shell to prototype your application is also useful in the development step.

Shell variables

Defining variables
When you define a variable, the variable name is not a dollar sign ($), such as:

Variablename= "Value"

Note that there can be no space between the variable name and the equals sign, which may be different from any programming language you know. At the same time, the name of the variable must follow the following rules:

The first character must be a letter (a-z,a-z).
You cannot have spaces in the middle, you can use an underscore (_).
You cannot use punctuation marks.
You cannot use the keywords in bash (you can view reserved keywords using the help command).

Using variables
Using a defined variable, just precede the variable name with the dollar sign ($), such as:

Your_name= "Tom"
Echo $your _name
Echo ${your_name}

The curly braces outside the variable name are optional, plus all rows, and curly braces are designed to help the interpreter identify the bounds of the variable, such as the following:

For skill in Ada coffe Action Java do
echo "I am good at ${skill}script"
Done

If the skill variable is not curly braces, written as echo "I am good at $skillScript", the interpreter takes $skillscript as a variable (its value is empty), and the code execution results are not what we expect.

It is a good programming practice to recommend all variables plus curly braces.
Redefining variables
Defined variables that can be redefined, such as:

Your_name= "Tom"
Echo $your _name

Your_name= "Alibaba"
Echo $your _name

This is legal, but note that the second assignment can not write $your_name= "Alibaba", the use of variables to add the dollar ($).

Shell annotations

Lines that begin with "#" are comments that are ignored by the interpreter.

There is no multiline comment in sh, only one line plus a # number. Can only be like this:

#--------------------------------------------
# This is a script that automatically plays IPA, based on Webfrogs's ipa-build writing:
# ps://github.com/webfrogs/xcode_shell/blob/master/ipa-build ' >https://github.com/webfrogs/xcode_shell/blob/ Master/ipa-build

# Features: Automatically packaged for Etao iOS app, 14-channel IPA package
# Features: Automatic packaging, no need to enter any parameters
#--------------------------------------------

##### User Configuration area starts #####
#
#
# project root directory, it is recommended to put this script in the root directory of the project, there is no need to change the
# application name to ensure consistency with the Target_name.app name under Xcode product
#
##### User Configuration area End #####

What if, during the development process, a large segment of code needs to be annotated temporarily and then canceled? Each line with a # symbol is too laborious, you can put this paragraph to annotate the code in a pair of curly braces, defined as a function, no place to call the function, the code will not be executed, to achieve the same effect as the annotation.

Shell string


Strings are the most commonly used data types in shell programming (except numbers and strings, and nothing else works), strings can be in single quotes, double quotes, or without quotes. The difference between single and double quotes is similar to PHP.
Single quotation mark

Str= ' This is a string '

Single quote string limit:

Any character in the single quotation mark is output as it is, and the variable in the single quote string is invalid;
Single quotation marks cannot appear in single quote strings (not after using escape characters for single quotes).

Double quotes

Your_name= ' QINJX '
Str= "Hello, I Know your are" $your _name "! N

Advantages of double quotes:

You can have variables in double quotes.
Escape characters can appear in double quotes

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

Extract substring

String= "Alibaba is a great company"
Echo ${string:1:4} #输出liba

Find substring

String= "Alibaba is a great company"
echo ' expr index ' $string ' is '

Shell Array

Bash supports one-dimensional arrays (multidimensional arrays are not supported) and does not qualify the size of the array. Similar to the C language, the subscript of an array element is numbered starting with 0. Gets the elements in the array to use the subscript, the subscript can be an integer or an arithmetic expression with a value greater than or equal to 0.
Defining arrays
In the shell, parentheses are used to represent the array, and the array elements are separated by a "space" symbol. The general form of the definition array is:
Array name = (value 1 value 2 ...) Value N)
For example:

Array_name= (value0 value1 value2 value3)

Or

Array_name= (
Value0
Value1
value2
Value3
)


You can also define individual components of an array individually:

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

You can not use consecutive subscript, and there is no limit to the scope of the subscript.
Reading arrays
The general format for reading array element values is:
${array name [subscript]}
For example:

Valuen=${array_name[n]}

Use the @ symbol to get all the elements in an array, for example:

Echo ${array_name[@]}

Get the length of an array
The method of getting the length of an array is the same as getting the length of the string, for example:

# 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 echo directive


ECHO is an internal instruction of the shell to print out the specified string on the screen. Command format:

Echo Arg

You can use echo to achieve more complex output format control.
Show escape characters

echo "" It is a test ""

The result will be:
"It is a test"

Double quotes can also be omitted.
Show variables

Name= "OK"
echo "$name It is a test"

The result will be:
OK It is a test

The same double quotation marks can also be omitted.

You need to use curly braces ({}) if the variable is connected to another character:

Mouth=8
echo "${mouth}-1-2009"

The result will be:
8-1-2009
Show Line Wrapping

echo "Ok!n"
echo "It is a test"

Output:
Ok!
It is a test
Show No Line wrapping

echo "Ok!c"
echo "It is a test"

Output:
Ok! It si a test
Show results directed to file

echo "It is a test" > myfile

Output string AS-is
Use single quotes if you want to output strings as they are (without escaping). For example:

Echo ' $name '

Show command Execution results

Echo ' Date '

The result displays the current date

Shell Test command

The test command in the shell is used to check whether a condition is valid, and it can be tested in three aspects, such as numeric value, character, and file.
Numerical test
Parameter description
-eq equals is True
-ne is not equal to true
True if-GT is greater than
-ge greater than or equal to true
-lt is true if it is less than
-le is less than or equal to true

For example:

num1=100
num2=100
if test $[num1]-eq $[num2]
Then
Echo ' The two numbers are equal! '
Else
Echo ' The two numbers are not equal! '
Fi

Output:
The two numbers are equal!
String test
Parameter description
= Equal to True
!= Not Equal is true
-Z String string length pseudo is True
-N String string length false is True

For example:

num1=100
num2=100
if test num1=num2
Then
Echo ' The two strings are equal! '
Else
Echo ' The two strings are not equal! '
Fi

Output:
The two strings are equal!
File test
Parameter description
-e filename is true if the file exists
-r file name if the file exists and is readable it is true
-W filename True if the file exists and is writable
-X file name if file exists and executable is true
-s filename If the file exists and at least one character is true
-d file name if the file exists and is true for the directory
-F filename is true if the file exists and is a normal file
-C filename is true if the file exists and is a character special file
-B filename True if the file exists and is a block special file
For example:

Cd/bin
If Test-e./bash
Then
Echo ' The file already exists! '
Else
Echo ' The file does not exists! '
Fi

Output:
The file already exists!

In addition, the shell provides a (!), or (-O), non (-a) three logical operators to connect test conditions with a priority of: "!" Highest, "-a" second, "-O" lowest. For example:

Cd/bin
If Test-e./notfile-o./bash
Then
Echo ' one file exists at least! '
Else
echo ' Both dose not exists! '
Fi

Output:
One file exists at least!

Shell if Else statement


Unlike Java, PHP and other languages, the process control of SH is not NULL, such as:

<?php
if (Isset ($_get["Q"])) {
Search (q);
}
else {
Doing nothing
}
?>

You can't write this in Sh/bash, if the Else branch has no statement execution, don't write this else, like this:

If condition
Then
Command1
Command2
...
CommandN
Fi

Of course, you can also write a line (for the terminal command prompt), like this:

if test $[2*3]-eq $[1+5]; Then echo ' The two numbers are equal! '; Fi

The end of the fi is the if reverse spelling, you will encounter similar.

If Else format

If condition
Then
Command1
Command2
...
CommandN
Else
Command
Fi


if else-if else format

If Condition1
Then
Command1
Elif Condition2
Command2
Else
CommandN
Fi


The If Else statement is often used in conjunction with the Test command, as follows:

NUM1=$[2*3]
NUM2=$[1+5]
if test $[num1]-eq $[num2]
Then
Echo ' The two numbers are equal! '
Else
Echo ' The two numbers are not equal! '
Fi

Output:
The two numbers are equal!

Shell Case Statement


The Shell Case statement is a multiple-selection statement. You can use a case statement to match a value with a pattern, and if the match succeeds, execute the matching command. The case statement is formatted as follows:

Case value in
Mode 1)
Command1
Command2
...
CommandN
;;
Mode 2)
Command1
Command2
...
CommandN
;;
Esac

The case works as shown above. The value must be followed by the word in, and each pattern must end with a closing parenthesis. The value can be a variable or a constant. When a match finds a value that conforms to a pattern, all commands begin to execute until;

The value will detect each pattern that matches. Once the pattern matches, the corresponding command after the match pattern is executed and no more mode continues. If there is no matching pattern, use the asterisk * to capture the value, and then execute the following command.

The following script prompts you to enter 1 to 4, matching each pattern:

Echo ' Input a number between 1 to 4 '
Echo ' Your number Is:c '
Read Anum
Case $aNum in
1) echo ' you select 1 '
;;
2) echo ' You select 2 '
;;
3) echo ' you select 3 '
;;
4) echo ' You select 4 '
;;
*) echo ' You don't select a number between 1 to 4 '
;;
Esac

Input different content, there will be different results, such as:
Input a number between 1 to 4
Your number Is:3
you select 3

Shell for Loop

Like other programming languages, the shell supports A for loop.

For loops The general format is:

For variable name in list
Todo
Command1
Command2
...
CommandN
Done

When the value of the variable is in the list, the For loop executes all the commands at once, using the variable name to get the current value in the list. The command can be any valid shell command and statement. The in list can contain replacements, strings, and file names.

The in list is optional, and if it is not used, the For loop uses the positional parameters of the command line.

For example, sequentially prints a number in the current list:

For loop in 1 2 3 4 5
Todo
echo "The value is: $loop"
Done

Output:
The value is:1
The value Is:2
The value Is:3
The value Is:4
The value Is:5

Characters in the sequential output string:

For str in ' it ' a string '
Todo
Echo $str
Done

Output:
This is a string


Shell While Loop


The while loop is used to continuously execute a series of commands and to read data from an input file; a command is usually a test condition. The format is:

While command
Todo
Command1
Command2
...
CommandN
Done

command completes, control returns to the top of the loop, starting from scratch until the test condition is false.

The following is a basic while loop, where the test condition is: If counter is less than 5, then the condition returns True. Counter starting from 0, counter plus 1 each time the loop is processed. Run the above script, return the number 1 to 5, and then terminate.

Counter=0
While [$COUNTER-lt 5]
Todo
counter= ' Expr $COUNTER +1 '
Echo $COUNTER
Done

Run script, Output:
1
2
3
4
5

The while loop can be used to read keyboard information. In the following example, the input information is set to the variable film, and the <Ctrl-D> ends the loop.

echo ' type <CTRL-D> to terminate '
Echo-n ' Enter your most liked film: '
While Read FILM
Todo
echo "yeah! Great film The $FILM "
Done

Run the script with the output similar to the following:
Type <CTRL-D> to terminate
Enter your most liked film:sound of Music
yeah! Great film The Sound of Music

Shell until loop


The Until loop executes a series of commands until the condition is true. The Until loop and the while loop are just the opposite of how they are handled. The general while loop is better than the until loop, but at some point-and only in rare cases, the until loop is more useful.

The Until loop format is:
Until conditions
Command1
Command2
...
CommandN
Done
The condition can be any test condition, the test occurs at the end of the loop, so the loop executes at least once-please note this.


Shell Break and Continue command


During the loop, there are times when you need to force out of the loop without reaching the end of the loop, and the shell uses two commands to implement the function: Break and continue.
Break command
The break command allows you to jump out of all loops (terminating all loops after execution).

In the following example, the script goes into a dead loop until the user enters a number greater than 5. To jump out of this loop, return to the shell prompt with the break command.

#!/bin/bash
While:
Todo
Echo-n "Input a number between 1 to 5:"
Read Anum
Case $aNum in
1|2|3|4|5) echo "Your number is $aNum!"
;;
*) echo "You don't select a number between 1 to 5, game is over!"
Break
;;
Esac
Done

Continue
The continue command is similar to the break command, except that it does not jump out of all loops and simply jumps out of the current loop.

Modify the example above to:

#!/bin/bash
While:
Todo
Echo-n "Input a number between 1 to 5:"
Read Anum
Case $aNum in
1|2|3|4|5) echo "Your number is $aNum!"
;;
* echo "You don't select a number between 1 to 5!"
Continue
echo "Game is over!"
;;
Esac
Done

Running code found that when you enter a number greater than 5, the loop in the example does not end, and the statement

echo "Game is over!"

Will never be executed.


Shell Functions


All scripts so far in this tutorial have been executed from beginning to end. This is good, but you may have noticed that some of the script segments are duplicated.

The shell allows a set of command sets or statements to be formed into a usable block called a shell function.

Functions in the shell are defined in the following format:
Function name () {
Command1
Command2
...
CommandN
[Return value]
}

If you prefer, you can precede the function name with a keyword function, depending on the user.
function functions name () {
Command1
Command2
...
CommandN
[Return value]
}

function returns a value that shows the increment return statement, and if not, the last command runs as the returned value (typically 0, which returns an error code if execution fails). Return followed by a value (0-255).

A function can be placed in the same file as a piece of code, or it can be placed in a separate file that contains only functions. A function does not have to contain many statements or commands, and it can even contain only one echo statement, depending on the consumer.

The following example defines a function and makes a call:

#!/bin/bash
Demofun () {
echo "This is your-a-function!"
}
echo "Function begin ..."
Hello
echo "Function end!"

Output:
Function begin ...
This is your the function!
Function end!

The following defines a function with a return statement:

#!/bin/bash
Funwithreturn () {
echo "The ' function is ' to ' the sum of two numbers ..."
Echo-n "Input A:"
Read Anum
Echo-n "Input Another number:"
Read Anothernum
echo "The two numbers are $aNum and $anotherNum!"
Return $ (($aNum + $anotherNum))
}
Funwithreturn
echo "The sum of two numbers is $?!"

The output is similar to the following:
The function is to get the sum of two numbers ...
Input number:25
Input another number:50
The two numbers are and 50!
The sum of two numbers is 75!

function returns the value after calling the function through $? To obtain.

Note: All functions must be defined before they are used. This means that you must place the function at the beginning of the script until the shell interpreter discovers it for the first time. Call functions use only their function names.


Shell Function Arguments


In a shell, you can pass arguments to a function when it is called. Inside the function body, the value of the parameter is obtained in the form of $n, for example, the first argument is represented, and the second argument is $ $ ...

Examples of functions with parameters:

#!/bin/bash
Funwithparam () {
echo "The value of the ' the ' the ' the ' the ' parameter ' is $!
echo "The value of the second parameter is $!"
echo "The value of the tenth parameter is $!"
echo "The value of the tenth parameter is ${10}!"
echo "The value of the eleventh parameter is ${11}!"
echo "The amount of the parameters is $#!"
echo "The string of the parameters is $*!"
}
Funwithparam 1 2 3 4 5 6 7 8 9 34 73

Output:
The value of the ' the ' is 1!
The value of the second parameter is 2!
The value of the tenth parameter is 10!
The value of the tenth parameter is 34!
The value of the eleventh parameter is 73!
The amount of the parameters is 12!
The string of the parameters is 1 2 3 4 5 6 7 8 9 34 73!

Note that $ cannot get the tenth argument, and getting the tenth argument requires ${10}. When n>=10, you need to use ${n} to get the parameters.

In addition, there are several special characters to handle parameters:
Parameter processing instructions
$# the number of arguments passed to the script
$* displays all parameters passed to the script in a single string
$$ the current process ID number of the script run
$! ID number of the last process running in the background
$@ and $ #相同, but use quotes and return each argument in quotation marks.
The $-displays the current options used by the shell, as is the SET command function.
$? Displays the exit status of the last command. 0 indicates no errors, and any other value indicates an error.

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.