- Linux自動化運維:Shell與Ansible(微課版)
- 楊寅冬主編
- 767字
- 2024-07-26 17:04:25
任務1.4.2 數據輸入輸出操作
1. 任務描述
編寫Shell腳本,通過數據輸入輸出與用戶交互,使用戶輸入數據或輸出信息;通過數據輸入輸出讀取文件中的數據或寫入數據到文件中;通過數據輸入輸出可以與其他程序或系統交互,以獲取或輸出數據。使用read命令讀取用戶輸入的數據,使用echo或printf命令輸出信息。
2. 任務實施
(1)使用read命令讀取用戶輸入的數據。
[opencloud@server ~]$ vim printf01.sh #!/bin/bash # 讀入用戶輸入的數字 read -p "Enter a number: " num # 輸出用戶輸入的數字 echo "You entered: $num" # 執行腳本并查看輸出結果 [opencloud@server ~]$ bash printf01.sh Enter a number: 100 You entered: 100
(2)使用read命令讀取多個數據。
[opencloud@server ~]$ vim printf02.sh #!/bin/bash # 讀取多個數據 read -p "Enter your name, age and gender: " name age gender # 輸出數據 echo "Name: $name" echo "Age: $age" echo "Gender: $gender" # 執行腳本并查看輸出結果 [opencloud@server ~]$ bash printf02.sh Enter your name, age and gender: Tom 18 male Name: Tom Age: 18 Gender: male
(3)使用read命令讀取文件中的每一行內容。
[opencloud@server ~]$ cat file.txt www.opencloud.fun www.redhat.com Linux Shell and Ansible [opencloud@server ~]$ vim printf03.sh #!/bin/bash # 讀取文件中的每一行內容 while read line; do # 輸出讀取的每一行內容 echo $line done < file.txt # 執行腳本并查看輸出結果 [opencloud@server ~]$ bash printf03.sh www.opencloud.fun www.redhat.com Linux Shell and Ansible
(4)使用printf命令格式化輸出數字。
[opencloud@server ~]$ vim printf04.sh #!/bin/bash printf "%.2f\n" 3.14159265 printf "%.4f\n" 3.14159265 printf "%d\n" 123456 printf "%x\n" 255 # 執行腳本并查看輸出結果 [opencloud@server ~]$ bash printf04.sh 3.14 3.1416 123456 ff
(5)使用printf命令格式化輸出字符串。
[opencloud@server ~]$ vim printf05.sh #!/bin/bash printf "%-10s %-8s %-4s\n" Name Gender Age printf "%-10s %-8s %-4d\n" John Male 30 printf "%-10s %-8s %-4d\n" Mary Female 25 # 執行腳本并查看輸出結果 [opencloud@server ~]$ bash printf05.sh Name Gender Age John Male 30 Mary Female 25
(6)使用printf命令輸出多個字符和字符串。
[opencloud@server ~]$ vim printf06.sh #!/bin/bash printf "%s %s %s\n" A B C printf "%s %s %s\n" A B C D E F G # 定義字符變量 char='a' # 使用 %c格式化輸出字符 printf "The character is %c.\n" $char # 定義字符串變量 string="Hello, World!" # 使用 %s格式化輸出字符串 printf "The string is %s.\n" "$string" # 使用 %-10s格式化輸出左對齊的字符串 printf "%-10s\n" "$string" # 執行腳本并查看輸出結果 [opencloud@server ~]$ bash printf06.sh
(7)使用printf命令輸出變量值。
[opencloud@server ~]$ vim printf07.sh #!/bin/bash name="John" age=30 printf "My name is %s, and I am %d years old.\n" "$name" "$age" # 上面的腳本中定義了兩個變量:name和age # 使用printf命令輸出字符串,并使用 %s和 %d占位符引用變量 # printf命令可以使用多個參數,使用變量時需使用$調用變量 # 執行腳本并查看輸出結果 [opencloud@server ~]$ bash printf07.sh My name is John, and I am 30 years old.
推薦閱讀
- Citrix XenApp Performance Essentials
- 每天5分鐘玩轉Kubernetes
- VMware Horizon View 6 Desktop Virtualization Cookbook
- 操作系統基礎與實踐:基于openEuler平臺
- SharePoint 2013 應用開發實戰
- 混沌工程:復雜系統韌性實現之道
- Linux操作系統應用編程
- Learning Bootstrap
- Windows 7案例教程
- Linux命令行大全(第2版)
- 一學就會:Windows Vista應用完全自學手冊
- Windows 8實戰從入門到精通(超值版)
- 大學計算機應用基礎實踐教程(Windows 7+MS Office 2010)
- Office 365 User Guide
- 鴻蒙HarmonyOS應用開發入門