bash编程:练习题
1. 写一个脚本:如果某路径不存在,则将其创建为目录;否则显示其存在,并显示内容类型
#!/bin/bash # baseurl=/var/tmp/testdir if [ -e $baseurl ]; then echo "file is no exists." else mkdir -p $baseurl file $baseurl fi
2. 写一个脚本,完成如下功能;判断给定的两个数值,孰大孰小;给定数值的方法:脚本参数,命令交互
#!/bin/bash # if [ $# -lt 1 ]; then echo "Plz enter two digit" exit 1 fi if [ $1 -gt $2 ]; then echo "MAX;$1 MIN:$2" else echo "MAX:$2 MIN:$1" fi
3. 求100以内所有奇数之和(至少用3种方法)
(1) #!/bin/bash # declare -i sum=0 for i in $(seq 1 2 100); do sum+=$i done echo " sum: $sum." (2) #!/bin/bash # declare -i sum=0 for i in {1..100}; do if [ $[$i%2] -eq 1 ]; then sum=$(($sum+$i)) fi done echo "Sum: $sum" (3) #!/bin/bash # declare -i sum=0 he () { for i in $(seq 1 2 100); do sum=$(($sum+$i)) done } he echo " sum: $sum."
4. 写一个脚本实现如下功能:
(1) 传递两个文本文件路径给脚本;
(2) 显示两个文件中空白行数较多的文件及其空白行的个数;
(3) 显示两个文件中总行数较多的文件及其总行数;
#!/bin/bash # #if [ $# -lt 1 ]; then # echo "Plz enter two Opt." # exit 1 #fi space1=$(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 ]; then echo "kongduode is /root/file: $space1 Lines" else echo "kongduode is /root/file1: $space2 Lines" fi if [ $line1 -gt $line2 ]; then echo "zonghangduo is /root/file: $line1 Lines" else echo "zonghangduo is /root/file1: $line2 Lines" fi
5. 写一个脚本
(1) 提示用户输入一个字符串;
(2) 判断:
如果输入的是quit,则退出脚本;
否则,则显示其输入的字符串内容;
#!/bin/bash # while true; do read -p "Plz enter character :" -t 10 char [ $char == "quit" ]&& break echo "character is A : $char" done
6. 写一个脚本,打印2^n表;n等于一个用户输入的值
#!/bin/bash # read -p "Plz enter a num :" -t 10 num declare -i i=0 while [ $i -le $num ];do let i++ echo -n -e "2^$i=$[2**$i]" echo done
7. 写一个脚本,写这么几个函数:函数1、实现给定的两个数值的之和;函数2、取给定两个数值的最大公约数;函数3、取给定两个数值的最小公倍数;关于函数的选定、两个数值的大小都将通过交互式输入来提供。备注:实在不懂公约数,公倍数,抄的邱野同学的作业
#!/bin/bash # if [[ $1 -eq "" ]];then echo ‘plz input the first number‘ exit 1 fi if [[ $2 -eq "" ]];then echo ‘plz input the second number‘ exit 2 fi function add() { sum=$[$1+$2] echo "the sum is $sum" } add $1 $2 declare -i max declare -i min if [[ $1 -gt $2 ]];then max=$1 min=$2 elif [[ $1 -lt $2 ]];then max=$2 min=$1 else max=$1 min=$2 fi function gong() { r=$[$max%$min] temp=$min declare -i a declare -i b if [[ $r -eq 0 ]];then echo "gongyue is $min" echo "gongbei is $max" else while [[ $r -ne 0 ]];do a=$2 b=$r r=$[$a%$b] done gongyue=$b gongbei=$[$1*$2/$b] echo "gongyue is $gongyue" echo "gongbei is $gongbei" fi } gong $1 $2
原文地址:http://zhangnan30.blog.51cto.com/2051991/1696863