- Linux自動化運維:Shell與Ansible(微課版)
- 楊寅冬主編
- 245字
- 2024-07-26 17:04:24
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
推薦閱讀
- Containerization with LXC
- Linux運維實戰:CentOS7.6操作系統從入門到精通
- Cybersecurity:Attack and Defense Strategies
- Persistence in PHP with the Doctrine ORM
- Instant Handlebars.js
- Ganglia系統監控
- 玩到極致 iPhone 4S完全攻略
- Windows Server 2012網絡操作系統企業應用案例詳解
- Instant Optimizing Embedded Systems using Busybox
- Linux自動化運維:Shell與Ansible(微課版)
- Android物聯網開發細致入門與最佳實踐
- CentOS 6 Linux Server Cookbook
- Windows 7實戰從入門到精通
- Windows Server 2008組網技術與實訓(第3版)
- Android應用性能優化最佳實踐