shell脚本基础练习

基础练习题

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

①编辑.sh文件时自动生成关于脚本文件说明的注释

[root@RHCE11 ~]# vim /root/.vimrc
autocmd BufNewFile *.py,*.cc,*.sh,*.java exec ":call SetTitle()"
func SetTitle()
  if expand("%:e") == 'sh'
     call setline(1,"#!/bin/bash")
     call setline(2,"#########################")
     call setline(3,"#File name:".expand("%"))
     call setline(4,"#Version:v1.0")
     call setline(5,"#Email:admin@test.com")
     call setline(6,"#Created time:".strftime("%F %T"))
     call setline(7,"#Description:")
     call setline(8,"#########################")
     call setline(9,"")
  endif
endfunc

②创建文件并编辑(vim中的+表示跳到文件的最后一行)

[root@RHCE11 ~]# mkdir /chap01
[root@RHCE11 ~]# cd /chap01
[root@RHCE11 chap01]# vim + ./test0.sh
#!/bin/bash
#########################
#File name:./test0.sh
#Version:v1.0
#Email:admin@test.com
#Created time:2023-12-03 16:19:44
#Description:
#########################
read -p "please input a number:" n
echo `seq -s "+" $n`=$[`seq -s "+" $n`]

③修改所属者的权限(注意:./filename.sh这样的文件会产生子进程再运行,使用脚本里面指定的shell去运行,因此,使用该种方式执行需要x权限

[root@RHCE11 chap01]# chmod u+x ./test0.sh

④测试

[root@RHCE11 chap01]# ./test0.sh
please input a number:10
1+2+3+4+5+6+7+8+9+10=55

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

①编辑文件

[root@RHCE11 chap01]# vim + ./test1.sh
#!/bin/bash
#########################
#File name:./test1.sh
#Version:v1.0
#Email:admin@test.com
#Created time:2023-12-03 16:35:26
#Description:
#########################
read -p 'input file:' file
echo ${file%/*}
echo .${file##*.}

②修改权限

[root@RHCE11 chap01]# chmod u+x ./test1.sh

③测试

[root@RHCE11 chap01]# ./test1.sh
input file:/etc/shell/test1.th
/etc/shell
.th

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

①编辑文件

[root@RHCE11 chap01]# vim + ./test2.sh
#!/bin/bash
#########################
#File name:./test2.sh
#Version:v1.0
#Email:admin@test.com
#Created time:2023-12-03 16:39:27
#Description:
#########################
read -p 'input number:' num
echo ${#num}

②修改权限

[root@RHCE11 chap01]# chmod u+x ./test2.sh

③测试

[root@RHCE11 chap01]# ./test2.sh
input number:1234
4

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

①编辑文件

[root@RHCE11 chap01]# vim + ./test3.sh
#!/bin/bash
#########################
#File name:./test3.sh
#Version:v1.0
#Email:admin@test.com
#Created time:2023-12-03 16:41:58
#Description:
#########################
read -p 'input a dir:' dir
ls $dir | wc -l

②修改权限

[root@RHCE11 chap01]# chmod u+x ./test3.sh

③测试

[root@RHCE11 chap01]# ./test3.sh
input a dir:/root
1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值