【问题标题】:Bash - Only When Output Is TerminalBash - 仅当输出为终端时
【发布时间】:2022-01-20 07:30:53
【问题描述】:

我希望我的代码中有一个部分仅在终端打印输出时执行,而不是通过管道传输或重定向到文本文件或其他程序中。

我试过这个:

#!/bin/bash

if [[ $(tty "-s") ]]; then
  printf "You are using a terminal.\n"
else
  printf "You are not using a terminal.\n"
fi

tty -s && printf "Guten Tag.\n"

./tty.sh 命令后的输出:

You are not using a terminal.
Guten Tag.

在 `./tty.sh > test.txt` 之后的 test.txt 中输出:
``` 你没有使用终端。 古腾标签。 ```

【问题讨论】:

标签: bash pipe tty


【解决方案1】:

请记住,bash 中的 if 语句会检查所提供命令的退出状态:

if command; then
  # then block
else
  # else block
fi

[[ 只是一个特殊的内置命令。

简单使用:

if tty -s; then

tty -s存在且退出状态为0时运行一些代码,(成功)

另外,不要使用tty 来检查输入是否是终端,而是使用[ -t 0 ]

if [ -t 0 ]; then

参见man 1 ttyman 1 test

如果从man 1 test 中不清楚,那么您可以分别测试标准输出和标准错误输出是否是一个终端:

[ -t 1 ] # stdout is a terminal
[ -t 2 ] # stderr is a terminal 

【讨论】:

  • 虽然这是一个很好的答案,但当我将输出重定向到文件时,此处建议的代码仍将被执行。
  • 如果您有兴趣测试您的输出,那么您可以更改为[ -t 1 ]
猜你喜欢
  • 2013-07-31
  • 1970-01-01
  • 1970-01-01
  • 2013-04-05
  • 2015-08-06
  • 1970-01-01
  • 1970-01-01
  • 2021-11-14
  • 1970-01-01
相关资源
最近更新 更多