Bash 程序 returns 输入时为 1,否则为 0

Bash program that returns 1 on input and 0 otherwise

是否有一个标准的 linux 终端程序,当给定文本输入(在标准中)时 returns 如果没有提供文本则为 1 和 0? (反逻辑也可以)。

例子

echo hello | unknown_program  # returns 1
echo | unknown_program        # returns 0

编辑:

我的用例用于从 C++ 程序调用程序,它应该不知道它在驱动器上的位置。这就是为什么我不喜欢创建脚本文件,而是使用我认为存在于任何 linux(或 ubuntu 在我的情况下)计算机上的应用程序。

这是 C++ 代码,但这不是问题的一部分。

auto isConditionMet = std::system("git status --porcelain | unknown_program");

我得到了一个有效的答案,所以至少我很高兴。

grep -q '.' 会这样做。 . 匹配除换行符之外的任何字符。 grep returns 一个 0 静态代码(成功)如果有任何匹配,并且 1 如果没有匹配。

echo hello | grep -q '.'; echo $? # echoes 0
echo | grep -q '.'; echo $? # echoes 1

如果您也想忽略仅包含空格的行,请将 . 更改为 [^ ]

与bash:

#!/usr/bin/env bash

if [[ -t 0 ]]; then
    echo "stdin is the TTY, no input has been redirected to me"
    exit 0
fi

# grab all the piped input, may block
input=$(cat)
if [[ -z $input ]]; then
    echo "captured stdin is empty"
    exit 0
fi

echo "I captured ${#input} characters of data"
exit 1

如果将其另存为 ./test_input 并使其可执行,则:

$ ./test_input; echo $?
stdin is the TTY, no input has been redirected to me
0

$ ./test_input < /dev/null; echo $?
captured stdin is empty
0

$ echo | ./test_input; echo $?
captured stdin is empty
0

$ ./test_input <<< "hello world"; echo $?
I captured 11 characters of data
1

$ echo foo | ./test_input; echo $?
I captured 3 characters of data
1

请注意,shell 的命令替换 $(...) 删除了所有尾随换行符,这就是 echo | ./test_input 案例报告未捕获任何数据的原因。

使用wc -w计算字数,使用shell算法检查条件,得到0或1到echo

echo | echo "$(("$(wc -w)" > 0))"                       # echoes 0
echo hello world | echo "$(("$(wc -w)" > 0))" # echoes 1