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

任務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.

主站蜘蛛池模板: 蓬莱市| 湘西| 航空| 平顺县| 马关县| 大厂| 黄冈市| 嫩江县| 民勤县| 遵化市| 集安市| 茶陵县| 成都市| 嘉黎县| 屏东市| 鄄城县| 景洪市| 平武县| 象山县| 舞钢市| 汝南县| 宝鸡市| 龙胜| 大埔区| 浮梁县| 铁岭县| 巴中市| 龙口市| 林西县| 阿拉善左旗| 德钦县| 赤壁市| 大渡口区| 通海县| 含山县| 敦化市| 濮阳市| 泌阳县| 抚顺县| 岐山县| 视频|