我知道人們通常在 Linux 命令提示符下(而不是在腳本中)使用 grep。我碰巧將 grep 放在腳本中并遇到了一個奇怪的情況。如果 grep 命令什么都不回傳,則下一行 echo 不起作用。下面是腳本。
grep "abc" /home/testuser/myapp.log
echo "abc"
這是grep的正常行為嗎?如果是,為什么?
uj5u.com熱心網友回復:
它似乎set -e在您的腳本中啟用。
通常情況下,grep如果選擇了一行,則退出狀態為 0,如果沒有選擇任何行,則為 1,如果發生錯誤則為 2。但是請注意,如果使用 -q 或 --quiet 或 --silent 并選擇了一行,即使發生錯誤,退出狀態也是 0。在您的情況下,如果abc在 中未找到/home/testuser/myapp.log,grep則回傳 1。
該bash外殼通常會在腳本執行下一行,也就是說echo "abc"即使grep收益為1的退出狀態但是,如果set -e被啟用,bash也不會在你的腳本執行任何更多的線路。
從bash聯機幫助頁:
-e Exit immediately if a pipeline (which may consist of a single simple command), a list, or a compound command
(see SHELL GRAMMAR above), exits with a non-zero status. The shell does not exit if the command that fails is
part of the command list immediately following a while or until keyword, part of the test following the if or
elif reserved words, part of any command executed in a && or || list except the command following the final &&
or ||, any command in a pipeline but the last, or if the command's return value is being inverted with !. If a
compound command other than a subshell returns a non-zero status because a command failed while -e was being
ignored, the shell does not exit. A trap on ERR, if set, is executed before the shell exits. This option ap‐
plies to the shell environment and each subshell environment separately (see COMMAND EXECUTION ENVIRONMENT
above), and may cause subshells to exit before executing all the commands in the subshell.
If a compound command or shell function executes in a context where -e is being ignored, none of the commands
executed within the compound command or function body will be affected by the -e setting, even if -e is set and
a command returns a failure status. If a compound command or shell function sets -e while executing in a con‐
text where -e is ignored, that setting will not have any effect until the compound command or the command con‐
taining the function call completes.
uj5u.com熱心網友回復:
您可以使用以下命令echo與grep:
printf "%s\n" "$(grep -o "abc" /home/testuser/myapp.log)"
參考
- grep 手冊頁
- 如何在 Unix shell 腳本中使用帶有 grep 的 echo?
uj5u.com熱心網友回復:
“下一行回聲不起作用”是什么意思?是echo不是在所有達到?它是否運行但產生非零退出代碼?或者你abc在輸出上看到了嗎?了解你的腳本將回傳任何的grep,和別的一無所知對腳本的其余部分,我可以說,在腳本輸出什么stdout的grep命令,并abc在stdout為echo。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/392358.html
上一篇:Grep計數有2個要求
