Print the return status of command execution in Shell

Source: Internet
Author: User

Sometimes, the execution path of the entire shell script file is determined based on the command execution result status.

A simple requirement is to determine whether a row of content exists in a file. If yes, no operation is performed. Otherwise, the row is inserted.

To determine whether a row exists in the file, run the grep command: grep $ line $ file.

If $ line exists in $ file, the result returned by grep execution is 0. If no result exists, 1 is returned. If $ file does not exist, 2 is returned.

We can use the following shell code for simple verification:

#/Bin/bashgrep "ABC" filenamereval =$? Echo "grep return value: $ reval" Exit 0

If you replace grep "ABC" filename in the preceding shell file with other required commands, you can print the execution result status at the end of the command.

But it is troublesome to modify the shell file every time. We can use the "·" symbol to directly test the file in the terminal window. Before "·" is closed, commands are not executed.

:~ $ Echo '> grep "ABC" FILENAME> reval = $?> Echo "grep return value: $ reval"> exit 0> 'grep: Filename: no such file or directorygrep return value: 2iie @ haproxy091 :~ $

As shown in the prompt, 2 is returned for grep execution because the file filename is found.

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.