Unix / Linux shell script in action "set -e" of

What "set -e" yes?

The following script:

#!/bin/bash
set -e
command 1
command 2
...

In the beginning of the script plus set -e, sentence statement tells bash If the results of any statement is not true, you should quit.

What "set -e" role?

  • (1) using the -e help you check for errors;

  • (2) prevent errors snowball increases lead to a fatal error, and the errors should have before it is disposed of;

  • (3) To increase readability, it can be used set -o errexit, and it acts set -ethe same;

What "set -e" disadvantage is that?

  • (1) can not be checked $?, since if the statement is not executed returns 0, bash can not perform a check code, shaped like the following script:

    #!/bin/bash
    set -e
    ...
    command  <== 执行的语句不是返回0,bash将不会往下执行if语句
    if [ $? -eq 0 ];then   
    echo "command failed";   
    exit 1;   
    fi
  • (2) cause the code can not be executed, for example as follows:

    #!/bin/bash
    set -e
    ...
    /home/work/.../hadoop dfs -rmr /app/.../dir
    /home/work/.../hadoop dfs -mkdir /app/.../dir
    /home/work/.../hadoop dfs -put file_1 /app/.../dir/
    ...

    These lines hadoop command logic is simple: Clear and create a new directory on hdfs, and push the files to a local directory for later use. These lines alone carry out, execute the command line, in addition to suggesting to delete the directory does not exist, and there is no problem, the file will still be pushed to the designated place.

    But when the first execution of the script, but pulled out of the failure, and lead to the overall program calls the script exits, causing serious consequences. The reason is not yet on hdfs this directory, rmr this line returns 255, this value is in front of the script "set -e" to capture, a direct result of the script exits.

    Description ⚠️:

    Visible Set "set -e", may be helpful in the script development process, and after the development is completed, in particular, may have to upgrade script for the latter, it may be buried a security risk.

Reference Documents

Guess you like

Origin blog.51cto.com/wutengfei/2428217