"If 'tty>/dev/null2> & 1 '"

Source: Internet
Author: User
& Quot; if 'tty & gt;/dev/null2 & gt; & amp; 1' & quot ;#! /Bin/basconditioned 'tty & gt;/dev/null2 & gt; & amp; 1'; thenecho & quot; interactive & quot; elseecho & quot; non-interactive & quot; fi ------ "if 'tty>/dev/null 2> & 1 '"#! /Bin/bash if 'tty>/dev/null 2> & 1 '; then echo "interactive" else echo "non-interactive" fi ------------------------------ cut here ------------------------ The "if 'tty>/dev/null 2> & 1 '" statement is one of those cute little unix tricks that requires a little explanation. knowing that the tty command will either yield a string such as "/dev/pts/2" or will issue the phrase "not a tty", we need Determine which response we get to determine whether or not we have a controlling terminal. = One way we cocould do this wocould be to construct an (excuse the pun !) Awkward command such as this: if ['tty | awk-F/'{print $2} ''=" dev "]; then This command wocould strip out the string "dev" from "/dev/pts/2" or, in the case of a non-interactive execution, yield a null string. this wocould work, but the command used in our skeletal script is considerably more efficient. let's look at it again: if 'tty>/dev/null 2> & 1'; then By tossing out the output from the tty command, the "tty>/dev/null 2> & 1" command leaves us with only the return code from the tty command to evaluate. if the tty command is run interactively (I. e ., with a controlling terminal), the return code is 0 (success ). when run non-interactively (I. e ., no controlling terminal), the return code is 1. our simple logic boils down to "if true, do this, otherwise ". this is, of course, the essence of any if statement, but we have arrived at our determination of true/false with very little processing and very little coding. thanks to Brian Hatch for recommending use of the tty command for determining whether a script is being run interactively.
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.