官术网_书友最值得收藏!

1.4 項目實施

任務1.4.1 輸入輸出重定向

1. 任務描述

編寫并執行簡單的Shell腳本,使用輸入輸出重定向及管道符將腳本的信息重定向到文件。

2. 任務實施

(1)創建Shell腳本firstscript.sh,使用vim文本編輯器在用戶家目錄下創建一個新的文本文件,將其命名為firstscript.sh,插入以下文本并保存文件,將輸入重定向到文件中。


[opencloud@server ~]$ cat input.txt 
2021 
2022 
2023 
2024 
2035 
2025 
1999 
2000 
2001 
[opencloud@server ~]$ vim firstscript.sh 
[opencloud@server ~]$ cat firstscript.sh 
#!/bin/bash 
# 從文件中讀取輸入 
sort < input.txt 

(2)使用bash命令執行腳本。


[opencloud@server ~]$ bash firstscript.sh
[opencloud@server ~]$ cat input.txt

(3)將輸出寫入文件中。


ls -l > output.txt

(4)追加輸出到文件中。


ls -l >> output.txt

(5)將標準錯誤輸出重定向到文件中。


ls -l /non-existent-dir 2>error.log

(6)使用輸入重定向忽略read命令的輸入。


#!/bin/bash
# 忽略read命令的輸入
read -p "Enter your name: " name < /dev/null
echo "Your name is: $name"

(7)從標準輸入中讀取多行文本。


#!/bin/bash
echo "Enter some text (Ctrl+D to finish):"
cat << EOF
This is line 1
This is line 2
This is line 3
EOF

(8)將多行文本輸出到文件。


#!/bin/bash
cat << EOF > output.txt
This is new line 1
This is new line 2
This is new line 3
EOF

(9)將多行文本追加到文件。


#!/bin/bash
cat << EOF >> output.txt
This is line 4
This is line 5
This is line 6
EOF

主站蜘蛛池模板: 开化县| 伊吾县| 岢岚县| 奈曼旗| 尉氏县| 丹寨县| 贵南县| 大方县| 景宁| 农安县| 崇仁县| 东山县| 齐河县| 龙山县| 南充市| 亳州市| 普兰店市| 高邮市| 孙吴县| 东丽区| 都兰县| 封开县| 梅河口市| 乌恰县| 乌苏市| 抚州市| 阜平县| 华容县| 新闻| 冕宁县| 铜山县| 海丰县| 灵武市| 富川| 霞浦县| 盐津县| 葫芦岛市| 盐津县| 平塘县| 青浦区| 延寿县|