是否有一個標準的 linux 終端程式,當給定文本輸入(在標準輸入中)時,如果沒有提供文本,則回傳 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");
我得到了一個有效的答案,所以至少我很高興。
uj5u.com熱心網友回復:
grep -q '.'會這樣做。.匹配除換行符以外的任何字符。如果有任何匹配項,并且沒有匹配項,則grep回傳靜態代碼(成功) 。01
echo hello | grep -q '.'; echo $? # echoes 0
echo | grep -q '.'; echo $? # echoes 1
如果您也想忽略僅包含空格的行,請更改.為[^ ].
uj5u.com熱心網友回復:
使用 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案例報告未捕獲資料的原因。
uj5u.com熱心網友回復:
用于計算單詞,并使用wc -wshell 演算法檢查條件并得到 0 或 1 到echo.
echo | echo "$(("$(wc -w)" > 0))" # echoes 0
echo hello world | echo "$(("$(wc -w)" > 0))" # echoes 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/466165.html
上一篇:在bash腳本中列印環境變數
