(五)linux函数及综合练习

函数:
函数语法:
函数一般定义在shell脚本中使用

function name ()
{

}

shell函数可以带function关键字,也可以不带
shell函数内可以加return返回值,也可以不带,如果不带就以最后一条命令运行结果,作为返回值。

例如:

demoFun(){
    echo "这是我的第一个 shell 函数!"
}
echo "-----函数开始执行-----"
demoFun
echo "-----函数执行完毕-----"

综合练习
1.判断用户如果不存在就创建用户 ,如果存在就打印用户id

1 #!/bin/bash
  2 if [ $# -ne 1 ];then
  3    echo "args errors,should hava one arg"
  4    exit 1
  5 fi
  6 user=$1
  7 if grep -q "^$user" /etc/passwd
  8 then
  9    echo "$user is alive,id is $(id -u $user)"
 10 else
 11    echo "$user is not alived,creating"
 12    useradd $user
 13    if [ $? -eq 0 ]
 14    then
 15     echo "create user success"
 16    else
 17         echo "create user failed"
 18    fi
 19 fi

2.写一个脚本模拟Linux登录

while read -p "localhost login: " user
do
 if [[ $user == "" ]]
 then
    continue
 fi
 read -s -p "Password: " passwd
 if [ $user == "root" -a  X$passwd == X"123456" ]
 then
           echo "" 
   while read -p "[$user@myterminal ~]#" cmd
   do
      $cmd
    done
 else
           echo "Login incorrect"
 fi 
 done

3.写一个shell脚本来替换系统的rm命令,要求当删除一个文件或者目录时,都要做一个备份,然后再删除。

  1 #!/bin/bash
  2 if [ $# -eq 0 ]
  3 then
  4    echo "must have a arg at least"
  5    exit 1
  6 fi
  7 
  8 file=$1
  9 dest=/tmp
 10 if [ ! -f $file ]
 11 then
 12    echo "$file doesn't exist"
 13    exit 1
 14 else
 15    cp $file $dest/
 16    if  [ $? -eq 0 ]
 17    then
 18       echo "backup success,deleting..."
 19       rm $file
 20    else
 21       echo "backup failed,do not rm $file"

4.编写shell脚本,把/root/目录下的所有目录(只需要一级)拷贝到/tmp/目录下

dir='/root'
subdir=`ls /root`
for i in $subdir
 do
    if [ -d $dir/$i ]
    then
 cp -r $dir/$i /tmp/
    fi
 done

5.请用shell编写一个等腰三角形,接收用户输入的数字

left=$(($1-1))
count=1
move=$left
or i in `seq $1`
 do
   for j in `seq $move`;do
     echo -n " "
   done
   for k in `seq $count`;do
     echo -n "*"
   done
   for j in `seq $move`;do
     echo -n " "
   done
   echo 
   count=$((count+2))
   move=$((move-1))
 done
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值