"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 to determine which response we get to determine whether or not we have a controlling terminal.


=One way we could do this would be to construct an (excuse the pun!) awkward command such as this:


if [ `tty | awk -F/ '{print $2}'` == "dev" ]; then
This command would strip out the string "dev" from "/dev/pts/2" or, in the case of a non-interactive execution, yield a null string. This would 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.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值