shell逆序输出数字和倒序打印字符串练习

1.你需要打印一个给定的数字的反序,如输入10572,输出27501,如果没有输入数据,应该抛出错误和使用脚本说明。

方法1:使用shell中的rev命令。

#!/bin/bash
read -p "please input a num:" num
if [ -z $num ]
then
  echo "Error!The input cannot be empty."
elif ! expr $num + 1 &> /dev/null
then
  echo "Error!The input must be a integer."
else
  echo $num > /tmp.txt
  rev /tmp.txt
fi
rm -f /tmp.txt

方法2:除十余数法

#!/bin/bash
read -p "please input a num:" num
if [ -z $num ]
then
  echo "Error!The input cannot be empty."
elif ! expr $num + 1 &> /dev/null
then
  echo "Error!The input must be a integer."
else
  while [ $num -ge 10 ]
  do
      echo -n `expr $num % 10`
      let num/=10
  done
  echo $num
fi

2.写出SHELL函数RevertInput,函数必须获取三个参数,然后将三个参数倒序echo打印出来,函数必须检查参数个数的合法性,如果参数非法,打印”Illegal parameters”,对于下面的输入: RevertInput “this is para1” para2 para3 应该输出: para3 para2 this is para1 (注:需要注意第一个参数中的空格)

#!/bin/bash
RevertInput () {
if  [ ! $# -eq 3 ]
then
  echo "illegal parameters"
else
  echo "$3 $2 $1"
fi
}
RevertInput "$1" "$2" "$3"

要注意最后一行不能写为 RevertInput $@ 或 RevertInput $1 $2 $3 ,否则一个带有空格的参数在传入函数时会被处理为多个参数

你可能感兴趣的:(Linux,linux,运维,shell)