'Bash program that returns 1 on input and 0 otherwise
Is there a standard linux terminal program that when given text input (in standard in) returns a 1 and 0 if no text is provided? (The reverse logic would also be fine).
Example
echo hello | unknown_program # returns 1
echo | unknown_program # returns 0
Edit:
My usecase, is for calling a program from a c++-program, that should be agnostic to where on the drive it resides. Thats why i do not prefer to create a script file, but using applications that i would assume exist on any linux (or ubuntu in my case) computer.
This is the c++-code but that is not part of the question.
auto isConditionMet = std::system("git status --porcelain | unknown_program");
And I got a working answer, so at least I am happy.
Solution 1:[1]
grep -q '.' will do this. . matches any character except newline. grep returns a 0 static code (success) if there are any matches, and 1 if there are no matches.
echo hello | grep -q '.'; echo $? # echoes 0
echo | grep -q '.'; echo $? # echoes 1
If you want to ignore lines with just spaces as well, change . to [^ ].
Solution 2:[2]
With 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
If this is saved as ./test_input and made executable, then:
$ ./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
Note that the shell's command substitution $(...) removes all trailing newlines, which is why the echo | ./test_input case report no data has been captured.
Solution 3:[3]
Using wc -w to count words, and shell arithmetic to check condition and get 0 or 1 to echo.
echo | echo "$(("$(wc -w)" > 0))" # echoes 0
echo hello world | echo "$(("$(wc -w)" > 0))" # echoes 1
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | Léa Gris |
