2024/03/25

本文介绍了四个Bashshell编程练习题,包括数字倒序、素数检测、检查并操作家目录下的文件权限以及字符串逆置。每个示例展示了基础的脚本编写和文件系统操作技巧。
摘要由CSDN通过智能技术生成

一、练习题

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

二、思维导图

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值