一、练习题
1.输入数组,输出数组的所有元素,以及数组长度。
#!/bin/bash
read -a arr
echo ${arr[*]}
echo ${#arr[*]}
运行结果:
ubuntu@ubuntu:0322$ sudo bash test_1.sh
11 22 33 44 55 66
11 22 33 44 55 66
6
2.定义数组存储当前目录下的所有.sh文件,计算文件的个数。
#!/bin/bash
a=`ls *.sh`
arr=($a)
echo ${arr[*]}
echo ${#arr[*]}
运行结果:
ubuntu@ubuntu:0322$ bash test_2.sh
shll_1.sh shll_2.sh shll_3.sh shll_4.sh shll_5.sh shll_6.sh shll_7.sh shll_8.sh shll_9.sh test_1.sh test_2.sh
11
3.在终端输入字符串,存储到数组中,计算字符串的个数。
#!/bin/bash
arr=($*)
echo ${arr[*]}
echo ${#arr[*]}
运行结果:
ubuntu@ubuntu:0322$ bash test_3.sh aa bb cc dd ee
aa bb cc dd ee
5
4.输入一个秒数,输出几时几分几秒。
#!/bin/bash
read time
hour=$((time/3600))
min=$((time%3600/60))
sec=$((time%60))
echo $hour小时$min分钟$sec秒
运行结果:
ubuntu@ubuntu:0322$ bash test_4.sh
3661
1小时1分钟1秒
5.输入一个数,使用条件运算符实现,如果是水仙花则赋值1否则赋值0。
#!/bin/bash
read -p "请输入一个三位数:" a
x=$((a/100))
y=$((a/10%10))
z=$((a%10))
b=$((a==x**3+y**3+z**3?1:0))
echo $b
运行结果:
ubuntu@ubuntu:0322$ bash test_5.sh
请输入一个三位数:153
1 5 3
1
ubuntu@ubuntu:0322$ bash test_5.sh
请输入一个三位数:153
1
ubuntu@ubuntu:0322$ bash test_5.sh
请输入一个三位数:370
1
ubuntu@ubuntu:0322$ bash test_5.sh
请输入一个三位数:656
0
6.终端输入一个年份,使用条件运算符实现,如果是闰年则赋值1否则赋值0。
#!/bin/bash
read -p "输入年份" y
p=$[y%400==0||y%4==0&&y%100!=0?1:0]
echo $p
运行结果:
ubuntu@ubuntu:0322$ bash test_6.sh
输入年份2024
1
二、思维导图