反转字符串
#!/bin/sh
#test.sh
STR=$1
LEN=${#STR}
for((i=LEN;i>=0;i--))
do
trap 'echo "第$LINENO行操作之前i=$i"' DEBUG
trap '错误 $LINENO:' ERR
trap 'echo "结尾:"' EXIT
echo -n ${STR:i:1}
done
echo -e "\n"
运行
./test.sh 123456 > test.txt
123456是传入的参数,将运行结果输出到test.txt文件。
修改后:
fun(){
a=$1
len=${#a}
echo "反转前:$a"
echo "长度是$len"
for((i=$len-1;i>=0;i--))
do
trap 'echo "execute in lineno:$LINENO, the char is ${a:i:1}"' DEBUG
echo "char:${a:i:1}"
done
echo -e "\n"
}
read -p "please input a word you want to reverse:" str
fun $str > test.txt
反转字符的同时字符大小写互转,将调试信息保存到log.txt文件中
fun(){
#获取参数
a=$1
#取字符串长度
len=${#a}
echo "反转前:$a"
echo "长度是$len"
#遍历字符串
for((i=$len-1;i>=0;i--))
do
#从后向前依次取得字符
c=${a:i:1}
#清空log.txt
:>log.txt
#打印调试信息
trap 'echo "execute in lineno:$LINENO, the char is $c" >> log.txt' DEBUG
trap 'error occur in lineno:$LINENO >> test.txt' ERR
trap 'echo "end:" >> test.txt' EXIT
#判断字符类型
case $c in
#为大写字母时转为小写
[[:upper:]])
echo -n $c | tr [A-Z] [a-z];;
#为小写字母时转为大写
[[:lower:]])
echo -n $c | tr [a-z] [A-Z];;
#非字母不需改变
*)
echo -n "$c" ;;
esac
done
echo -e "\n"
}
#从键盘获取参数
read -p "please input a word you want to reverse:" str
#调用函数
fun $str