Linux bash Shell Process Control (IF/ELSE)

Source: Internet
Author: User
Tags builtin

This article transferred from: http://blog.csdn.net/flowingflying/article/details/5069646

 

  • This article is also the fifth chapter of the Learning the Bash Shell 3rd Edition flow control reading notes, but we will not be limited to this. Flow control is a very common part of any programming language, and it includes bash. Here, we will learn from them.

    If/else is judged by the choice of execution or execution of part of the code, can be based on variables, filenames, commands are executed successfully and many other criteria to judge, his format is as follows:

    if         condition             Then         Statements        [elif condition then statements ... ]        [Else statements ] fi

    Unlike the C program, Bash is judged not by Boolean, but by statement, which is the final state after the command is executed (exit status). All Linux commands, whether you are the code is C or script, are executed, all return an integer to notify him of the call this, this is exit status, usually 0 means OK, the other (1-255) indicates an error. This is only the usual situation, for example diff,0 indicates that your no difference,1 represents an error difference,2. If the last exit status of statements is judged, usually we only put a statement, if it is 0, that is true, otherwise it represents false.

    Executing the next command will flush out the original exit status. You can use $? To view the results of the previous command execution. For example, we want to replace the CD command that was originally compiled in Linux kernel with a new CD command, because function takes precedence over the built-in command, so when called, our function is called. Here's an example of function pushd, typing the dirname pathname of a CD in a stack, and performing a jump to that path.

    CD ()

    {

    #由于我们已经定义了具有更高优先级别的function, if you want to call the original built-in command, you need to precede the builtin.

    builtin CD "[Email protected]"

    #$? is the return value of the previous command, which is the value of the Builtin CD "[email protected]" and is recorded in result.

    result=$?

    echo "$OLDPWD-$PWD"

    #返回result的值. We need to note that the return in the shell is not the same as the return in other programs, such as the C language, and only represents the last exit statue, not the so-called return value, although it also uses return. How to have no final reture, for example, the Push_func,exit status in the back is the exit status of the last command executed

    return $result

    }

    Push_func ()

    {

    Dirname=$1

    #如果dirname为null, exit funcuntion, such as CD dirname success, push the directory, otherwise display still in $PWD, CD using function CD functions with a priority higher than the CD that has been compiled in the kernel

    if CD ${dirname:? "       Missing directory name. "} Then

    mystack= "$dirname ${mystack:-$OLDPWD}"

    Echo $mystack

    Else

    Echo still in $PWD.

    Fi

    }

    Push_func $

    combination of conditions

    Like the C language, you can combine conditions, use &&,| |, and! Three ways to denote "and", "or", and "non", in the following format:

  • If statement1 && statement2, if statement1 | | statement2 , if ! statement1 .

    Exit status is not a unique value to judge, you can use the [...] and [[...]].

    string comparison

    String comparisons are placed in the [...] , there are several of the following:

      • str1 = str2, string 1 matches string 2
      • Str1! = str2, string 1 mismatch string 2
      • str1 > Str2, String 1 is greater than String 2
      • str1 < str2, string 1 less than String 2
      • -N str, string not NULL, length greater than 0
      • -Z str, string null, zero length

      It is important to note that < and the > symbols are similar to the redirect symbols, in order to avoid ambiguity and errors, use if [ $a /> $b ] Way . Still the above example, we add pop_func to operate the stack:

    Pop_func ()

    {

    mystack=${mystack#*

    }

    #下面请至于 [...], that is, [there is a space behind,] preceded by a space, and another $mystack in double quotes, indicating that this represents a string. Notice that then do not put on the next line, with if put on one line, with;

    If [-N "$mystack"]; Then

    CD ${mystack%% *}

    echo "$PWD", stack is [$mystack]

    Else

    echo "Stack empty, still in $PWD."

    Fi

    }

    For example, we require the command to have parameters, except to use {1? " <message "}, the following is a more readable way:

    If [-Z ']; then echo ' usage:c filename [-n] ' exit 1 fi

    Here exit indicates end, exit, execution result is failed, nonzero.

    file attribute comparison

    File attribute comparisons are another common type of conditional judgments.

      • -a   file : File exists
      • -D   file : File exists and is a directory
      • -e   file : file exists, same-a
      • -F   File : File exists and is a regular (not a directory or other special type file)
      • -R   file : Read-only permission
      • -S   file : File exists and is not empty
      • -W   file : Write permission
      • Strong>-x file : Have execute permission or have Search permission for directory
      • -n   file : After the last read, File changed
      • -o   file : Own file
      • -G   file : The file that the group belongs to
      • file1 -nt   file2 : file1 than file2 update to the last updated time
      • file1 -ot   file2 : file1 is older than file2, whichever is the last update time

    These are in the [...] The conditions in the judgment can be multiple combinations, such as if [condition] && [condition]; Then, of course, if command && [condition]; Then, not by analogy. In particular, we can make a copy of the conditions to judge. You can also use- A and- o , which is equivalent to the logical calculation of & and | In C, and they and && are | | Similar. When they are used in condition.

    In the example above Push_func, in addition to judging whether the parameter is not, increase the judgment is the directory name, as follows:

            if [-n ' $dirname] &&[-D "$dirname"]         then              CD $dirname             mystack= "$dirname ${mystack:- $OLDPWD} "                     Echo $mystack         else              echo still in $PWD .                 fi

    We are adding a judgment at the time when the directory name is checked to see if it can be viewed or manipulated. Use if [-N ' $dirname] &&[- D "$dirname"-a-x "$dirname" ], but it's hard to read, we need to surround two of them, (- D "$dirname ")-A (-X" $dirname "). However (is a special match, need to use/(the way, that is: if [-N "$dirname"] &&[/(-D "$dirname"/)-A/(-X "$dirname"/)] .

    integer comparison

    > or < or = is a comparison for strings, and if used for integer comparisons, use:

      • -lt, less than
      • -le, less than or equal to
      • -eq, equal to
      • -ge, greater than or equal to
      • -GT, greater than
      • -ne, not equal to

Linux bash Shell Process Control (IF/ELSE)

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.