shell的变量——变量的运算

1、写一个shell脚本,计算1+2+……+n共n个值的和,n值由用户输入

#原理
[root@se7en shell]# a=10
[root@se7en shell]# seq -s '+' 1 $a
1+2+3+4+5+6+7+8+9+10
[root@se7en shell]# seq -s '+' 1 $a | bc
55

#配置文件
[root@se7en shell]# vim num.sh
[root@se7en shell]# cat num.sh
#!/bin/bash
read -p "please input a number,计算1+2+..+n:" n
echo `seq -s '+' 1 $n`=`seq -s '+' 1 $n | bc`

#提供权限
[root@se7en shell]# chmod a+rx num.sh

#验证
[root@se7en shell]# ./num.sh
please input a number:10
1+2+3+4+5+6+7+8+9+10=55

2、让用户输入一个文件名,分别输出该文件的所在目录和该文件的扩展名

#原理
[root@se7en shell]# filename=/etc/nginx/nginx.conf
[root@se7en shell]# echo ${filename%/*} 
/etc/nginx
[root@se7en shell]# echo ${filename##*.} 
conf

#配置文件
vim filename.sh
cat filename.sh
#!/bin/bash
read -p ":" filename
echo "文件所在目录:${filename%/*}"
echo "文件扩展名:${filename##*.}"

#提供权限
[root@se7en shell]# chmod a+rx filename.sh 

#验证
[root@se7en shell]# ./filename.sh
:/shell/test02/test1.sh
文件所在目录:/shell/test02
文件扩展名:sh

3、判断用户输入的数值是几位数

#原理
a=1234
expr length $a

#配置文件
[root@se7en shell]# vim length.sh
[root@se7en shell]# cat length.sh
#!/bin/bash
read -p "请输入数值:" num
echo 该数为 `expr length $num` 位数

#提供权限
[root@se7en shell]# chmod a+rx length.sh 

#验证
[root@se7en shell]# ./length.sh 
请输入数值:1234
该数为 4 位数

4、统计用户输入的目录文件中文件的个数

#配置文件
vim dirname.sh
cat dirname.sh
#!/bin/bash
read -p "请输入目录:" dirname
echo "$dirname中有`ls $dirname | wc -l`个文件"

#提供权限
[root@se7en shell]# chmod a+rx dirname.sh 

#验证
[root@se7en shell]# ./dirname.sh 
请输入目录:/shell/
/shell/中有10个文件

5、计算用户输入的任意两个整数的和、差、乘积、商、余数

方法一:

#配置文件
[root@localhost test4]# vim 1.sh 
[root@localhost test4]# cat 1.sh 
#!/bin/bash
a=$1
b=$2
echo a+b=$[a+b]
echo a-b=$[a-b]
echo a*b=$[a*b]
echo a/b=$[a/b]
echo a%b=$[a%b]

#提供权限
[root@se7en shell]# chmod a+rx ./1.sh

#验证
[root@localhost test4]# ./1.sh 10 3
a+b=13
a-b=7
a*b=30
a/b=3
a%b=1

方法二:

#配置文件
[root@localhost test4]# vim 2.sh
[root@localhost test4]# cat 2.sh 
#!/bin/bash
read -p "please input two number:" a b
echo $a+$b=$(($a+$b))
echo $a-$b=$[a-b]
echo $a*$b=$[a*b]
echo $a/$b=$[a/b]
echo $a%$b=$[a%b]

#提供权限
[root@se7en shell]# chmod a+rx 2.sh

#检验
[root@localhost test4]# ./2.sh 
please input two number:3 4
3+4=7
3-4=-1
3*4=12
3/4=0
3%4=3

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值