當在bash shell中運行命令時,通常會將命令的輸出列印到終端,以便可以立即看到輸出內容。但是bash還提供了一個選項,可以將任何bash命令的輸出“重定向”到日誌檔。它可以將輸出保存到文本檔中,以便以後在需要時可以對此文本檔進行查看。
方法1:僅將輸出寫入檔
要將Bash命令的輸出寫入檔,可以使用右尖括弧符號(>
)或雙右尖符號(>>
):
右尖括弧(>)
右尖括弧號(>
)用於將bash命令的輸出寫入磁片檔。如果沒有指定名稱的檔,則它將創建一個具有相同名稱的新檔。如果該檔案名稱已經存在,則會覆蓋原文件內容。
雙右尖括弧(>>)
它用於將bash命令的輸出寫入檔,並將輸出附加到檔中。如果檔不存在,它將使用指定的名稱創建一個新檔。
從技術上講,這兩個運算符都將stdout
(標準輸出)重定向到檔。
當第一次寫入檔並且不希望以前的數據內容保留在檔中時,則應該使用右尖括弧(>
)。也就是說,如果檔中已經存在內容,它會清空原有數據內容,然後寫入新數據。使用雙右尖括弧(>>
)則是直接將數據附加到檔中,寫入後的內容是原文件中的內容加上新寫入的內容。
示例ls
命令用於列印當前目錄中存在的所有檔和文件夾。但是,當運行帶有直角括弧符號(>
)的ls
命令時,它將不會在螢幕上列印檔和文件夾列表。而是將輸出保存到用指定的檔中,即如下腳本代碼所示:
#!/bin/bash
#Script to write the output into a file
#Create output file, override if already present
output=output_file.txt
#Write data to a file
ls > $output
#Checking the content of the file
gedit output_file.txt
執行上面示例代碼,得到以下結果:
如此處所示,ls
命令的輸出重定向到檔中。要將檔的內容列印到終端,可以使用以下cat
命令格式:
#!/bin/bash
#Script to write the output into a file
#Create output file, override if already present
output=output_file.txt
#Write data to a file
ls > $output
#Printing the content of the file
cat $output
執行上面示例代碼,得到以下結果:
如果要在不刪除原文件數據內容的情況下,將多個命令的輸出重定向到單個檔,則可以使用>>
運算符。假設要將系統資訊附加到指定的檔,可以通過以下方式實現:
#!/bin/bash
#Script to write the output into a file
#Create output file, override if already present
output=output_file.txt
#Write data to a file
ls > $output
#Appending the system information
uname -a >> $output
#Checking the content of the file
gedit output_file.txt
在這裏,第二條命令的結果將附加到檔末尾。可以重複幾次此過程,以將輸出追加到檔末尾。
執行上面示例代碼,得到以下結果:
方法2:列印輸出並寫入檔
有些人可能不喜歡使用>
或>>
運算符將輸出寫入檔,因為終端中將沒有命令的輸出。可以通過使用tee
命令將接收到的輸入列印到螢幕上,同時將輸出保存到檔中。
Bash腳本
#!/bin/bash
#Script to write the output into a file
#Create output file, override if already present
output=output_file.txt
#Write data to a file
ls | tee $output
執行上面示例代碼,得到以下結果:
與>
運算符一樣,它將覆蓋檔的原內容,但也會在螢幕上列印輸出。如果要在不使用tee
命令刪除檔內容的情況下將輸出寫入檔,則可以使用以下格式將輸出列印到終端,參考以下代碼:
#!/bin/bash
#Script to write the output into a file
#Create output file, override if already present
output=output_file.txt
echo "<<<List of Files and Folders>>>" | tee -a $output
#Write data to a file
ls | tee $output
echo | tee -a $output
#Append System Information to the file
echo "<<<OS Name>>>" | tee -a $output
uname | tee -a $output
執行上面示例代碼,得到以下結果:
上面示例不僅將輸出附加到檔末尾,而且還將輸出列印在螢幕上。