Shell-basic practice script (a must-see for novices)

1. Basic practice script questions

1. Exercise one

Check whether the test.sh file in the user's home directory exists, and check whether it has execute permission.

#!/bin/bash

if [ -f test.sh ];then
 echo "test.sh文件存在"

  if [ -x test.sh ];then
    echo "test.sh文件有执行权限"
  else
    echo "tset.sh文件没有权限"
  fi

else
 echo "tset.sh不存在"

fi

Insert picture description here
Insert picture description here

2. Exercise 2

Prompt the user to enter the number of seconds for the 100-meter race. It is required to determine whether the number of seconds is greater than 0 and less than or equal to 10 seconds to enter the trial. Those greater than 10 seconds are eliminated. If other characters are entered, they will be prompted to re-enter; the members who enter the trial will further judge the gender of men and women. , Boys enter the boys group, and girls enter the girls group. If you make a mistake, please indicate an error.

#!/bin/bash
read -p "输入100米赛跑秒数(1-100):" a

if [[ $a -gt 0 && $a -le 10 ]] &> /dev/null ;then
  echo '您以成功晋级选拔赛'

read -p "请输入你的性别(男/女):" b

  if [ $b = 男 ];then
    echo "您已进入男子组"
  elif [ $b = 女 ];then
    echo "您已进入女子组"
  else
    echo "请正确输入"
  fi

elif [ $a -gt 10 ] &> /dev/null ;then
  echo "您已被淘汰"
else
  echo "请正确输入"
fi

Insert picture description here
Insert picture description here

3. Exercise three

Use the case statement to decompress the compressed package with the suffix .tar.gz or .tar.bz2 to the /opt directory.

#!/bin/bash

case $1 in
*.tar.gz)
  if [ -f $1 ];then
    tar -zxvf $1 -C /opt &> /dev/null
  else
    echo "$1 不存在"
  fi
;;

*.tar.bz2)
  if [ -f $1 ];then
   tar -jxvf $1 -C /opt &> /dev/null
  else
   echo "$1 不存在"
  fi
;;

*)
  echo "文件输入错误" 
esac

Insert picture description here
Insert picture description here

4. Exercise four

Prompt the user to input content, use the if statement to determine whether the input content is an integer.

#!/bin/bash#整数
read -p "请输入数字:" a

if [ $a = 0 ];then
 echo "0 是整数"
else

  let i=a+0 &> /dev/null
  if [ $? = 0 ];then
    echo " $a 是整数"
  else
   echo " $a 不是整数"
  fi
  
fi                                                                                                                          

Insert picture description here
Insert picture description here

5. Exercise five

According to the previous question, judge whether the input is odd or even.

#!/bin/bash

read -p "请输入数字:" a

if [ $a = 0 ];then
 echo " 0 是整数也是偶数"

else
let i=a+0 &> /dev/null

  if [ $? = 1 ];then
  echo " $a 不是整数也不是奇偶数"
  else
     let b=a%2 &> /dev/null

     if [ $? = 1 ];then
       echo " $a 是整数是偶数"
     else
       echo " $a 是整数是奇数"
     fi
  fi
fi


Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/s15212790607/article/details/114376049