Getting Started with Shell learning

Source: Internet
Author: User

Impression, always think that as long as mastering the Linux command, natural for writing shell scripts will not be unfamiliar. This is not right. The first half of the sentence is true, it is necessary to master the Linux command, so as to write the use of efficient script, but the latter sentence is not correct. To write a shell script, You also need to master the Shell's internal commands, process controls, and redirects.

Recently the system has learned some shell's introduction, has a lot of new understanding, accumulates as follows.

1. Variables:

In the shell, the use of variables does not need to be declared, can be used directly, and there is no type of restriction, the same variable, different operations, determine the different types of variables, such as [$a = $b], where the variables A and B, is a string. But they were the same, [$a-gt $b], Here they are the numbers. Of course, this is only a special case, if the value of a is not a number, it will be an error.

Also need to be clear, Linux case sensitive, Shell nature is no exception.

It is also important to note that variable expansion, that is, the declaration of a variable, $AB will not be recognized as a value of B, but should be ${a}b. Another way of non-variable expansion is "$a" b

An environment variable, a special variable used to change the behavior of the shell. Commonly used have

$HOME the home path of the current user

$PATH the path to the search command for the current system

$PS 1 Command Prompt

$PS A 22-level prompt, that is, when the input command does not enter a complete prompt

$IFS field delimiter is by default a space, tab, line break

The name of the shell script

$# the number of shell script parameters

$$ the process number of the shell script

$ ... $n parameters for shell scripts

$* the shell script parameter list, which is affected by the domain delimiter.

[Email protected] Shell script parameter list, not affected by the domain delimiter.

For example:

2. Conditional judgment

Test and [], for the purpose of judgment, the two functions are exactly the same, you can use the test can be used [].

The current judgment can be broadly divided into three types,

The judgment of a string

[$string 1 = $string 2] strings are equal. You need to pay attention to the use of spaces.

[$string 1! = $string 2] string does not want to wait

[-N $string 1] string is not empty

[-Z $string 1] string is empty

Number comparison

[$a-eq $b] A and B are equal

[$a-ne $b] A and B are not equal

[$a-gt $b] a greater than B

[$a-ge $b] A is greater than or equal to B

[$a-lt $b] a less than b

[$a-le $b] A is less than or equal to B

[! A] A is false and the expression is true, note the use of spaces.

File judgment

-F is a normal file

-E exists, but there is a portability issue. Not every version of the shell supports this option

-D Whether it is a directory

-B is a block file.

-S whether the size is not 0

-R is readable

-W is writable

-X is executable

The above is true.

3. Process Control (if for and until case)

If you test a result, different work is done depending on the outcome.

Common if-control structures:

if [condition]

Then

Command

elif [Condition]

Then

Command

Else

Command

Fi

As an example:

#!/bin/bashecho What's it today?read dayif [$day = Sateday] | | [$day = Sunday]then    echo Oh good!!! else     echo Oh god...fi

This small example also includes a knowledge point, the command list of knowledge, a simple extension.

Command1 && command2 && command3 && ... This shell statement executes from left to right, and the first command that returns false is no longer executed.

Command1 | | Command2 | | Command3 | |   ..... This shell statement executes from left to right, and the first command that executes successfully is no longer executed.

The For Loop executes a command block.

Use the following:

For variable in range

Do

Something

Done

A range can be specified by curly braces, or it can be a command or a variable. As an example:

#!/bin/bash                                                                echo test for 1 for i in {a,b,c}                                                                                  Do                                                                            Echo-e "\t$i" done                                                                                                                                             echo Test for 1 end                                                                 echo Test for 2 For I in {d..                                 G} do                                                 Echo-e "\t$i"                                                                                                                                             Done echo test for 2 end E                                                               Cho test for 3 for I in ' seq 10 ' Do E                                                                            Cho-e "\t$i" done                                                                                                                                             echo Test for 3 end                                                            echo Test for 4     filelist=$ (LS) for i in $filelist                                                                                  Do                                                                            Echo-e "\t$i" done  echo Test for 4 end

whileLoop through a block of code but unlike for a, the while is followed by a conditional qualification, not a range. The while loop executes until the condition is false.

The basic usage is as follows:

While condition

Do

Something

Done

Can generally be used as a condition there are many, if the applicable in here also almost applies.

#!/bin/bashwhile read I do     echo $idone < For.shecho ' This is a test ' | While the read I do    echo $idone
It is important to note that the true and false in the shell can only be represented by the real (:), and the fake. If you use 0 or 1, that's wrong. For the shell, both 0 and 1 are true in the conditional judgment. And in this example above, the file for EOF represents the condition as false.


The until Loop executes a piece of code. And while in contrast, the until loop executes until the condition is true.

The usage is similar to while.

Until condition

Do

Something

Done

Ashamed that I could not think of an example to use. Copy a paragraph:

#!/bin/bashuntil who | grep "$" >/dev/nulldo    Sleep 60doneecho-e "\a" echo "$ logged"
This script means to specify a parameter, that is, $ $. If the user logged on to the system, the alarm is called and the message is printed and then exited. Otherwise, the loop waits.


The Case Branch statement, and if a bit similar I think, look at the usage bar.

Case variable in

PATTERN1) something;;

PATTERN2) something;;

Esac

Or an example to see how he uses it.

#!/bin/bashecho marry Me?read choicecase $choice in     y|y|[ YY][EE][SS])         echo Yes, I'll        ;    [nn]*]        echo You is good man,please don\ ' t let me hurt        ;;    *)         echo ni chi fan mei you        ;; Esac
Case statements can be selected in several ways, which are listed above.

y|y| [Yy] [Ee] [Ss]   #这段的意思是, whether the input Y or Y or Yes or Yes will be output yes,i would and *) means the equivalent of Default.<span style= "FONT-SIZE:18PX;" >4. Functions </span>

The Shell's function is simple. No parameters are required and return values are not required. That's all you need.

Func ()

{

Do something

}

But this function does not seem to be the same as the garbage, can not accept the parameters, and there is no way to output the results. Definitely not. The Shell function is interpreted as a script within a script, which means that he passes parameters in a manner similar to the way a shell script receives parameters. $ #表示函数的参数个数, [ Email protected] The argument list of the function $* is also the parameter list $1$2 is the 1th or 2 parameter of the function.

#!/bin/bashtest_master () {    if test $#-ne 2    then        echo-Input 2 parameter        exit    fi    Echo who is the master in your home?    For i in ' seq $# '    do        eval res= ' $ ' $i        if [$res! = "Alai"] then            echo $res        fi    done}test_mas ter Alai jingjing

5. Partial commands

The main concerns in this paragraph are built-in commands.

Break is used to jump out of a loop, as a built-in command. You can follow a number to indicate how many layers are bouncing. This is generally not recommended. It's easy to confuse code logic.

: Command This command is an empty command. It always means true, but it runs faster than true (as the book says, I'm not aware of it anyway), and the shell used to do it in a very early time: command-style as a script comment. Now unified Adoption #

Continue jump the next cycle, unity can be followed by a number to continue the nth loop, nor is it recommended.

. The command indicates that the command is executed in the current shell. Generally, we use the./method that generates a child process and then executes the script, using this command, to execute the command directly in the current process.

echo Print command. No explanation.

Eval This command is interesting and allows you to evaluate the parameters. It also has its usage when explaining the function. Don't forget the single quotation mark Kazakhstan.

Exit n ends the run of the script with the exit code N. For now, 0 indicates a successful run. The other indicates that the run failed. It is a good habit to use this command in a script.

Export imports the subsequent variables into the child shell.

Expr evaluates a parameter as an expression equivalent to $[] usage res= ' expr 1+2 '

Let action and expr are the same, there is a difference in the use of a=1+1 note there are no spaces. This should not be built-in.


That's a lot to summarize. Hopefully it will be helpful for the students to get started with the shell.

Getting Started with Shell 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.