在Bash Shell腳本中,可以使用多種方法來對(duì)文件進(jìn)行操作,包括讀取文件或?qū)懭胛募?/p>
1. 寫入文件
bash shell可以利用"重定向",將一些打印到終端的消息寫入到文件中,方便在需要時(shí)可以對(duì)此文件文件查看。
1.1 僅將輸出寫入文件
要將Bash命令的輸出寫入文件,可以使用右尖括號(hào)符號(hào)(>)或雙右尖符號(hào)(>>),兩個(gè)運(yùn)算符都將stdout(標(biāo)準(zhǔn)輸出)重定向到文件,區(qū)別在于:
- 右尖括號(hào)號(hào)(>)用于將bash命令的輸出寫入磁盤文件。如果沒有指定名稱的文件,則它將創(chuàng)建一個(gè)具有相同名稱的新文件。如果該文件名稱已經(jīng)存在,則會(huì)覆蓋原文件內(nèi)容。
- 它用于將bash命令的輸出寫入文件,并將輸出附加到文件中。如果文件不存在,它將使用指定的名稱創(chuàng)建一個(gè)新文件。
當(dāng)?shù)谝淮螌懭胛募⑶也幌M郧暗臄?shù)據(jù)內(nèi)容保留在文件中時(shí),則應(yīng)該使用右尖括號(hào)(>)。也就是說,如果文件中已經(jīng)存在內(nèi)容,它會(huì)清空原有數(shù)據(jù)內(nèi)容,然后寫入新數(shù)據(jù)。使用雙右尖括號(hào)(>>)則是直接將數(shù)據(jù)附加到文件中,寫入后的內(nèi)容是原文件中的內(nèi)容加上新寫入的內(nèi)容。
例子如下:
# The script is:
o_file=o_file.log
echo "new line1" > $o_file
# The result is:
the current directory will contain o_file.log file
1.2 打印輸出并寫入文件
可以通過使用tee命令將接收到的輸入打印到屏幕上,同時(shí)將輸出保存到文件中。
# The script is:
o_file=o_file.log
echo "new line1" | tee $o_file
# The result is:
1. terminal ouptut: new line1
2. And the current directory will contain o_file.log file
如果除了打印到屏幕,也要實(shí)現(xiàn)追加到文件末尾的功能的話,那么可以用tee -a的方式,例子如下:
# The script is:
o_file=o_file.log
echo "new line1" | tee -a $o_file
echo "new line2" | tee -a $o_file
# The result is:
1.
new line1
new line2
2.
And the current directory will contain o_file.log file
對(duì)比上述用法,除了tee會(huì)多將信息打印到終端上,其實(shí)>和tee功能類似,>>和tee -a功能類似。
2. 讀取文件
讀取文件的最簡(jiǎn)單方式就通過cat或$來進(jìn)行。格式如下:
# o_file.log content:
# new line1
# new line2
# The format is:
data0=`cat o_file.log`
echo $data0
data1=$(< o_file.log)
echo $data1
# The result is:
new line1 new line2
new line1 new line2
如果想要逐行讀取文件的內(nèi)容,那么可以采用以下方法:
# The script is:
while read line1;
do
echo $line1;
done < o_file.log
# The result is:
new line1
new line2
while循環(huán)將到達(dá)文件的每一行,并將該行的內(nèi)容存儲(chǔ)在$line1變量中。
-
存儲(chǔ)器
+關(guān)注
關(guān)注
38文章
7637瀏覽量
166519 -
Shell
+關(guān)注
關(guān)注
1文章
372瀏覽量
24026 -
bash終端
+關(guān)注
關(guān)注
0文章
7瀏覽量
2037
發(fā)布評(píng)論請(qǐng)先 登錄
如何在bash shell腳本中使用變量

shell腳本編寫之本地腳本的編寫和執(zhí)行
【RT-Thread學(xué)習(xí)筆記】bash和dash-shell

Raspberry Pi Bash Shell 腳本簡(jiǎn)介

如何在bash shell腳本中接受參數(shù)
bash腳本中的循環(huán)功能
shell腳本基礎(chǔ)知識(shí)
BASH shell腳本篇—條件命令

BASH shell腳本篇—字符串處理
BASH shell腳本篇—函數(shù)
shell并行調(diào)用腳本
Shell腳本檢查工具ShellCheck介紹

評(píng)論