簡體   English   中英

如何將 linux 命令行輸出保存到 .txt 文件?

[英]How to save linux command line outputs to a .txt file?

我想制作一個 .sh 可執行文件,輸入終端命令,並將輸出保存到 .txt 文件。

例如,獲取i2cdump的輸出並保存到文件中。 用於此的終端命令是

i2cdump -r -y 0x0-6 0 0x68
"outputs the specified bytes 0x0-6 to terminal window"

如何使用 .sh 可執行文件自動執行此操作,並將輸出保存到存儲在/dir/的文件中?

我為myfile.sh編寫的一些偽代碼:

#!/bin/bash

output=$(i2cdump -r -y 0x0-6 0 0x68)
FILE * fp;
// write output to file
// save to directory
close(fp)

您可以像這樣使用 shell 重定向:

echo "Hello world" > greetings.txt

或根據您的需要:

#!/bin/bash

i2cdump -r -y 0x0-6 0 0x68 > output.txt
# closing is automatic at the end of redirecting.

Bash 手冊中有關標准輸出流的 shell 重定向的一般信息:重定向

任何命令都可以附加 > 以重定向輸出。 如:

echo "foo" > /path/to/file

請注意,您應該知道兩件事: 1 ">" 正在覆蓋文件,而 >> 正在附加。 如:

echo "foo" > /path/to/file

文件內容將是:

盡管

echo "foo" > /path/to/file
echo "foo2" >> /path/to/file

文件內容將是:

foo2

而且,如果您想重定向錯誤,您可以使用 2 操作數。 如:

cat /path/to/non-existing-file 2> /outputfile

將所有操作的錯誤寫入outputfile 相同的>>>邏輯適用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM