bash编程:练习题
1. 写一个脚本:如果某路径不存在,则将其创建为目录;否则显示其存在,并显示内容类型
#!/bin/bash#baseurl=/var/tmp/testdirif [ -e $baseurl ]; thenecho "file is no exists."elsemkdir -p $baseurlfile $baseurlfi
2. 写一个脚本,完成如下功能;判断给定的两个数值,孰大孰小;给定数值的方法:脚本参数,命令交互
#!/bin/bash#if [ $# -lt 1 ]; thenecho "Plz enter two digit"exit 1fiif [ $1 -gt $2 ]; thenecho "MAX;$1 MIN:$2"elseecho "MAX:$2 MIN:$1"fi
3. 求100以内所有奇数之和(至少用3种方法)
(1) #!/bin/bash#declare -i sum=0for i in $(seq 1 2 100); dosum+=$idoneecho " sum: $sum."(2) #!/bin/bash#declare -i sum=0for i in {1..100}; doif [ $[$i%2] -eq 1 ]; thensum=$(($sum+$i))fidoneecho "Sum: $sum"(3) #!/bin/bash#declare -i sum=0he () {for i in $(seq 1 2 100); dosum=$(($sum+$i))done}heecho " sum: $sum."
4. 写一个脚本实现如下功能:
(1) 传递两个文本文件路径给脚本;
(2) 显示两个文件中空白行数较多的文件及其空白行的个数;
(3) 显示两个文件中总行数较多的文件及其总行数;
#!/bin/bash##if [ $# -lt 1 ]; then# echo "Plz enter two Opt."# exit 1#fispace1=$(grep "^$" /root/file |wc -l)space2=$(grep "^$" /root/file1 |wc -l)line1=$(cat /root/file |wc -l)line2=$(cat /root/file1 |wc -l)if [ $space1 -gt $space2 ]; thenecho "kongduode is /root/file: $space1 Lines"elseecho "kongduode is /root/file1: $space2 Lines"fiif [ $line1 -gt $line2 ]; thenecho "zonghangduo is /root/file: $line1 Lines"elseecho "zonghangduo is /root/file1: $line2 Lines"fi
5. 写一个脚本
(1) 提示用户输入一个字符串;
(2) 判断:
如果输入的是quit,则退出脚本;
否则,则显示其输入的字符串内容;
#!/bin/bash#while true; doread -p "Plz enter character :" -t 10 char[ $char == "quit" ]&& breakecho "character is A : $char"done
6. 写一个脚本,打印2^n表;n等于一个用户输入的值
#!/bin/bash#read -p "Plz enter a num :" -t 10 numdeclare -i i=0while [ $i -le $num ];dolet i++echo -n -e "2^$i=$[2**$i]"echodone
7. 写一个脚本,写这么几个函数:函数1、实现给定的两个数值的之和;函数2、取给定两个数值的最大公约数;函数3、取给定两个数值的最小公倍数;关于函数的选定、两个数值的大小都将通过交互式输入来提供。备注:实在不懂公约数,公倍数,抄的邱野同学的作业
#!/bin/bash#if [[ $1 -eq "" ]];thenecho 'plz input the first number'exit 1fiif [[ $2 -eq "" ]];thenecho 'plz input the second number'exit 2fifunction add() {sum=$[$1+$2]echo "the sum is $sum"}add $1 $2declare -i maxdeclare -i minif [[ $1 -gt $2 ]];thenmax=$1min=$2elif [[ $1 -lt $2 ]];thenmax=$2min=$1elsemax=$1min=$2fifunction gong() {r=$[$max%$min]temp=$mindeclare -i adeclare -i bif [[ $r -eq 0 ]];thenecho "gongyue is $min"echo "gongbei is $max"elsewhile [[ $r -ne 0 ]];doa=$2b=$rr=$[$a%$b]donegongyue=$bgongbei=$[$1*$2/$b]echo "gongyue is $gongyue"echo "gongbei is $gongbei"fi}gong $1 $2