简体   繁体   English

Bash - 仅当 Output 为终端时

[英]Bash - Only When Output Is Terminal

I want to have a section in my code that only executes, when the output is printed in the terminal, not piped or redirected into a text file or other program.我想在我的代码中有一个部分仅在终端中打印 output 时执行,而不是通过管道传输或重定向到文本文件或其他程序中。

I tried this:我试过这个:

#!/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"

Output after ./tty.sh command: ./tty.sh命令后的 Output:

You are not using a terminal.
Guten Tag.

Output in test.txt after `./tty.sh > test.txt`: `./tty.sh > test.txt`之后的test.txt中的Output:
``` Youre not using a terminal. ``` 你没有使用终端。 Guten Tag. 古腾标签。 ``` ```

Remember that if statements in bash checks the exit status of the provided command:请记住,bash 中的 if 语句会检查所提供命令的退出状态:

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

and [[ is just a special built-in command.[[只是一个特殊的内置命令。

Simply use:只需使用:

if tty -s; then

To run some code when tty -s exists with an exit status of 0, (success)tty -s存在且退出状态为 0 时运行一些代码,(成功)

And also instead of using the tty to check if the input is a terminal, use [ -t 0 ] instead.并且不要使用tty来检查输入是否是终端,而是使用[ -t 0 ]

if [ -t 0 ]; then

See man 1 tty and man 1 test .请参阅man 1 ttyman 1 test

In case it wasn't clear from the man 1 test , then you can test if standard output and standard error output is a terminal with, respectively:如果从man 1 test不清楚,那么您可以测试标准 output 和标准错误 output 是否分别是一个终端:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM