一、练习题
1.输入一个数,实现倒叙
#!/bin/bash
read -p "请输入一个数" x
value1=`expr length $x`
i=1
sum=0
m=1
while [ $i -le $value1 ]
do
value2=`expr substr $x $i 1`
((sum=sum+value2*m))
((m*=10))
((i++))
done
echo $sum
运行结果:
ubuntu@ubuntu:0325$ bash 6.sh
请输入一个数456789
987654
2. 输入一个数,判断是否是素数
#!/bin/bash
while [ true ]
do
read -p "请输入一个数" x
i=2
count=0
while [ $i -lt $x ]
do
if ((x%i==0))
then
((count++))
fi
((i++))
done
if ((count))
then
echo "$x不是素数"
else
echo "$x是素数"
fi
done
运行结果:
ubuntu@ubuntu:0325$ bash 7.sh
请输入一个数13
13是素数
请输入一个数14
14不是素数
请输入一个数15
15不是素数
请输入一个数16
16不是素数
请输入一个数17
17是素数
请输入一个数18
18不是素数
请输入一个数19
19是素数
3. 输入一个文件名
判断是否在家目录下存在,
如果是一个目录,则直接输出是目录下的.sh文件的个数
如果存在则判断是否是一个普通文件,
如果是普通文件则判断是否具备可读可写可执行权限,
如果具备权限,写入hello,
不具备权限,则添加读写执行权限,写入hello
如果是一个链接文件则输出文件的详细信息
#!/bin/bash
while [ true ]
do
read -p "请输入一个文件名" file1
if [ -e /home/ubuntu/$file1 ]
then
if [ -d /home/ubuntu/$file1 ]
then
iarr=(`ls /home/ubuntu/$file1/*.sh`)
echo "${#arr[*]}"
elif [ -L /hoem/ubuntu/$file1 ]
then
q=`ls -lh /home/ubuntu/$file1`
echo "$q"
elif [ -f ~/$file1 ]
then
if [ ! -r ~/$file1 ]
then
chmod u+r ~/$file1
fi
if [ ! -w ~/$file1 ]
then
chmod u+w ~/$file1
fi
if [ ! -x ~/$file1 ]
then
chmod u+x ~/$file1
fi
fi
echo hello >> ~/$file1
else
echo "该文件不存在"
fi
done
4.输入一个字符串,实现字符串逆置
#!/bin/bash
read -p "请输入一个字符串" str
i=1
a=
while [ $i -le ${#str} ]
do
a=$a${str:0-$i:1}
((i++))
done
echo $a
运行结果:
ubuntu@ubuntu:0325$ bash 9.sh
请输入一个字符串hello
olleh
二、思维导图