只有當命令成功時,我才嘗試將命令的輸出重定向到檔案中,因為我不希望它在失敗時擦除其內容。(command正在讀取檔案作為輸入)
我目前正在使用
cat <<< $( <command> ) > file;
如果檔案失敗,它會洗掉檔案。
可以通過將輸出存盤在這樣的臨時檔案中來做我想做的事情:
<command> > temp_file && cat temp_file > file
但它看起來有點亂,我想避免手動創建臨時檔案(我知道 <<< 重定向正在創建一個臨時檔案)
我終于想出了這個技巧
cat <<< $( <command> || cat file) > file;
這不會改變檔案的內容......但我猜這更混亂。
uj5u.com熱心網友回復:
也許將輸出捕獲到變數中,如果退出狀態為零,則將變數回顯到檔案中:
output=$(command) && echo "$output" > file
測驗
$ out=$(bash -c 'echo good output') && echo "$out" > file
$ cat file
good output
$ out=$(bash -c 'echo bad output; exit 1') && echo "$out" > file
$ cat file
good output
uj5u.com熱心網友回復:
請記住,>運算子將檔案的現有內容替換為命令的輸出。如果要將多個命令的輸出保存到單個檔案中,可以使用>>運算子。這會將輸出附加到檔案的末尾。
例如,以下命令會將輸出資訊附加到您指定的檔案中:
ls -l >> /path/to/file
因此,對于僅在成功時記錄命令輸出,您可以嘗試以下操作:
until command
do
command >> /path/to/file
done
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/478757.html
