Shell脚本练习

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

企业面试题

京东

问题1:使用Linux命令查询file1中空行所在的行号。

[root@server ~]# cat file1
问题1:使用Linux命令查询file1中空行所在的行号。
[root@server ~]# awk '/^$/{print NR}' file1
2

问题2:有文件chengji.txt内容如下''
张三 40
李四 50
王五 60
使用Linux命令计算第二列的和并输出。

[root@server ~]# cat chengji.txt
张三 40
李四 50
王五 60
[root@server ~]# awk '{sum+=$2}END{print sum}' chengji.txt
150

搜狐 讯网

问题1:Shell脚本里如何检查一个文件是否存在?如果不存在该如何处理?

[root@server ~]# cat 3.sh
#!/bin/bash
read -p "please input filename:" filename
if [ -f $filename ]
then
 echo "file exist"
else
 echo "file is not exist"
 touch $filename
fi

新浪

问题1:用shell写一个脚本,对文本中无序的一列数字排序

[root@server ~]# vim test.txt
[root@server ~]# vim sort.sh +
[root@server ~]# chmod 755  sort.sh
[root@server ~]# ./sort.sh
12
21
45
56
89
169
256
646
659
6595
7879
65965
[root@server ~]# cat sort.sh
#!/bin/bash
sort -n test.txt

金和网络

问题1:请用shell脚本写出查找当前文件夹(/home)下所有的文本文件内容中包含有字符”shen”的文件名称

小米

问题1:
一个文本文件info.txt的内容如下:
aa,201
zz,502
bb,1
ee,42
每行都是按照逗号分隔,其中第二列都是数字,请对该文件按照第二列数字从大到小排列

[root@server ~]# sort  -t "," -k 2 -nr info.txt

美团

问题1:编写脚本实现以下功能;
每天早上5点开始做备份
要备份的是/var/mylog里所有文件和目录可以压缩进行备份
备份可以保存到别一台器上192.168.1.2 FTP帐号 aaa 密码 bbb
要求每天的备份文件要带有当天的日期标记

[root@server ~]# vim bak.sh

#!/bin/bash
bakfir=log
date='date +%F'
cd /var
tar zcf ${bakdir}_${date}.tar.gz ${bakdir}
sleep 1
ftp -n <<- EOF
open 192.168.142.129 #远程ftp服务器IP
user aaa bbb
put mylog_*.tar.gz
bye
EOF

[root@server ~]# vim /etc/crontab
# For details see man 4 crontabs

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed
00 05 * * * /bin/bash /root/bak.sh

问题2:请用shell脚本创建一个组class、一组用户,用户名为stdX,X从01-30,并归属class组

#!/bin/bash
id -g class &>/dev/null || groupadd class
user=std
for i in {01..30}
do
id -u ${user}$i &>/dev/null || useradd -G class ${user}$i
done

百度

· ## 处理以下文件内容,将域名取出并进行计数排序,如处理:

http://www.baidu.com/more/
http://www.baidu.com/guding/more.html
http://www.baidu.com/events/20060105/photomore.html
http://hi.baidu.com/browse/
http://www.sina.com.cn/head/www20021123am.shtml
http://www.sina.com.cn/head/www20041223am.shtml

cut -d'/' -f3 test.txt | sort | uniq -c | sort -nr

奇虎360

1、写一个脚本查找最后创建时间是3天前,后缀是*.log的文件并删除。**

find / -name “*.log” -ctime +3 -exec rm -f {} \;

2、写一个脚本将某目录下大于100k的文件移动至/tmp下。

for i in `find /test -type f -size +100k`;do cd /test && mv $i /tmp;done

3、写一个脚本进行nginx日志统计,得到访问ip最多的前10个(nginx日志路
径:/home/logs/nginx/default/access.log

awk '{a[$1]++}END{for (j in a) print a[j],j}' /home/logs/nginx/default/access.log|sort -nr|head

4、写一个脚本把指定文件里的/usr/local替换为别的目录。

sed 's:/user/local:/tmp:g' filename

滴滴出行

1、指令:ls | grep “[ad]*.conf” 命令解释正确的是:
正确答案: B
A 显示包含a 或者d 为开头,后接任何字符,再后面是.conf字符的文件(或目录)
B 显示包含a 或者d 出现0 次或无数次,后面是.conf字符的文件(或目录)
C 显示包含字母a 或者d出现0次或1次,后面是.conf字符的文件(或目录)
D 显示从字母a 到d ,后接任何字符,再后面是.conf字符的文件(或目录)
2、找出IO重定向执行结果与其他三个不同的:
正确答案: B
A ./run.sh >run.log 2>&1;
B ./run.sh 2>&1 >run.log;
C ./run.sh &>run.log;
D ./run.sh 2>run.log >&2
3、一个文件,大概1亿行,每行一个ip,将出现次数最多的top10输出到一个新的文件中

awk -F" " '{IP[$1]++}END{for (i in IP) print IP[i],i}'  /var/log/filename.log  |sort -k2  -rn   |head -10  >text.txt


awk -F" " '{print $1}' /var/log/filename.log |sort -n  |uniq -c |sort -rn  -k1 |head -10  > text.txt 

练习

案例1:监控硬件信息

[root@master shell]# cat info.sh
#!/bin/bash
#显示服务器硬件信息.
echo -e "\033[34m---------服务器硬件信息---------\033[0m"
echo -e "\033[32m网卡信息如下:\033[0m"
ifconfig ens33 | grep "inet "   
# ifconfig 需要装包net-tools 注意网卡名称
echo -e "\033[32m剩余内存容量信息如下:\033[0m"
grep MemAvailable /proc/meminfo
echo -e "\033[32m磁盘容量信息如下:\033[0m"
df -h /
echo -e "\033[32mCPU信息如下:\033[0m"
grep "model name" /proc/cpuinfo

[root@master shell]# ./info.sh
---------服务器硬件信息---------
网卡信息如下:
        inet 192.168.11.112  netmask 255.255.255.0  broadcast 192.168.11.255
剩余内存容量信息如下:
MemAvailable:     596376 kB
磁盘容量信息如下:
Filesystem               Size  Used Avail Use% Mounted on
/dev/mapper/centos-root   17G  1.5G   16G   9% /
CPU信息如下:
model name      : AMD Ryzen 7 4800H with Radeon Graphics
model name      : AMD Ryzen 7 4800H with Radeon Graphics
model name      : AMD Ryzen 7 4800H with Radeon Graphics
model name      : AMD Ryzen 7 4800H with Radeon Graphics

案例2:数据计算

[root@master shell]# cat calc.sh
#!/bin/bash
#计算1+2+3,...,+n的和,可以使用n*(n+1)/2公式快速计算结果
read -p "请输入一个正整数:" num
sum=$[num*(num+1)/2]
echo -e "\033[32m$num以内整数的总和是:$sum\033[0m"

#使用三角形的底边和高计算面积:A=1/2bh
read -p "请输入三角形底边长度:" bottom
read -p "请输入三角形高度:" hight
A=$(echo "scale=1;1/2*$bottom*$hight" | bc)
echo -e "\033[32m三角形面积是:$A\033[0m"
#梯形面积:(上底边长度+下底边长度)*高/2
read -p "请输入梯形上底边长度:" a
read -p "请输入梯形下底边长度:" b
read -p "请输入梯形高度:" h
A=$(echo "scale=2;($a+$b)*$h/2" | bc)
echo -e "\033[32m梯形面积是:$A\033[0m"

#使用A=πr2公式计算圆的面积,取2位小数点精度,π=3.14
read -p "请输入圆的半径:" r
A=$(echo "scale=2;3.14*$r^2" | bc)
echo -e "\033[32m圆的面积是:$A\033[0m"

[root@master shell]# ./calc.sh
请输入一个正整数:6
6以内整数的总和是:21
请输入三角形底边长度:2
请输入三角形高度:3
三角形面积是:3.0
请输入梯形上底边长度:3
请输入梯形下底边长度:4
请输入梯形高度:2
梯形面积是:7.00
请输入圆的半径:5
圆的面积是:78.50

案例3:自动配置yum源

[root@master shell]# cat yum.sh
#!/bin/bash
#定义YUM源路径
URL=ftp://192.168.4.1/centos

#创建YUM源配置文件
echo "[CentOS]
name=centos
baseurl=$URL
gpgcheck=0" > /etc/yum.repos.d/yum.repo

[root@master shell]# cat /etc/yum.repos.d/yum.repo
[CentOS]
name=centos
baseurl=ftp://192.168.4.1/centos
gpgcheck=0

案例4:监控系统信息

[root@master shell]# cat info2.sh
#!/bin/bash
#本脚本获取系统各项性能参数指标,并与预设阈值进行比较

#time:时间,loalip:eth0网卡IP,free_mem:剩余内存大小,free_disk:剩余磁盘大小
#cpu_load:15min平均负载,login_user:登录系统的用户,procs:当前进程数量
local_time=$(date +"%Y%m%d %H:%M:%S")

#注意网卡名称,ifconfig需要安装net-tools
local_ip=$(ifconfig ens33 | grep netmask | tr -s " " | cut -d" " -f3)
free_mem=$(cat /proc/meminfo |grep Avai | tr -s " " | cut -d" " -f2)
free_disk=$(df | grep "/$" | tr -s " " | cut -d' ' -f4)
cpu_load=$(cat /proc/loadavg | cut -d' ' -f3)
login_user=$(who | wc -l)
procs=$(ps aux | wc -l)
#当剩余内存不足1GB时发送邮件给root进行报警
[ $free_mem -lt 1048576 ] && \
echo "$local_time Free memory not enough.
Free_mem:$free_mem on $local_ip" | \

#安装mailx工具
mail -s Warning root@localhost
#当剩余磁盘不足10GB时发送邮件给root进行报警
[ $free_disk -lt 10485760 ] && \
echo "$local_time Free disk not enough.
root_free_disk:$free_disk on $local_ip" | \
mail -s Warning root@localhost
#当CPU的15min平均负载超过4时发送邮件给root进行报警
result=$(echo "$cpu_load > 4" | bc)
[ $result -eq 1 ] && \
echo "$local_time CPU load to high
CPU 15 averageload:$cpu_load on $local_ip" | \
mail -s Warning root@localhost
#当系统实时在线人数超过3人时发送邮件给root进行报警
[ $login_user -gt 3 ] && \
echo "$local_time Too many user.
$login_user users login to $local_ip" | \
mail -s Warning root@localhost
#当实时进程数量大于500时发送邮件给root进行报警
[ $procs -gt 500 ] && \
echo "$local_time Too many procs.
$procs proc are runing on $local_ip" | \
mail -s Warning root@localhost

案例5:判断用户名与密码是否为空

版本1:
[root@master shell]# cat user_v1.sh
#!/bin/bash
read -p "请输入用户名:"   user
read -s -p "请输入密码:"   pass
if [ ! -z "$user" ];then
    useradd  "$user"
fi
if [ ! -z "$pass" ];then
    echo "$pass" | passwd --stdin "$user"
fi
echo

版本2:
[root@master shell]# cat user_v2.sh
#!/bin/bash

read -p "请输入用户名:" user
read -s -p "请输入密码:"   pass
if [ ! -z "$user" ] && [ ! -z "$pass" ];then
    useradd "$user"
    echo "$pass" | passwd --stdin "$user"
fi

案例6:测试主机是否ping通

[root@master shell]# cat if_ping.sh
#!/bin/bash
#ping通脚本返回up,否则返回down

if [ -z "$1" ];then
    echo -n "用法: 脚本 "
    echo -e "\033[32m域名或IP\033[0m"
    exit
fi
#-c(设置ping的次数),-i(设置ping的间隔描述),-W(设置超时时间)
ping -c2 -i0.1 -W1 "$1" &>/dev/null
if [ $? -eq 0 ];then
    echo "$1 is up"
else
    echo "$1 is down"
fi

案例7:猜数字

[root@master shell]# cat guess_num.sh
#!/bin/bash
#脚本自动生成10以内的随机数,根据用户的输入,输出判断结果.
clear
num=$[RANDOM%10+1]
read -p "请输入1-10之间的整数:" guess
if [ $guess -eq $num ];then
    echo "恭喜,猜对了,就是:$num"
elif [ $guess -lt $num ];then
    echo "Oops,猜小了."
else
    echo "Oops,猜大了."
fi

案例8:打印九九乘法表

[root@master shell]# cat 99.sh
#!/bin/bash

for((i=1;i<=9;i++))
do
   for((j=1;j<=i;j++))
   do
      echo -n "$i*$j=$[i*j] "
   done
   echo
done

案例9:猜随机数

[root@master shell]# cat guess_random.sh
#!/bin/bash
num=$[RANDOM%10+1]
while :
do
read -p "请输入1-10之间的整数:" guess
if [ $guess -eq $num ];then
    echo "恭喜,猜对了,就是:$num"
    exit
elif [ $guess -lt $num ];then
    echo "Oops,猜小了."
else
    echo "Oops,猜大了."
fi
done

案例10:一键部署FTP服务器

[root@master shell]# cat install_vsftp.sh
#!/bin/bash

#安装ftpd软件,修改配置文件,设置匿名用户可以上传文件.
if rpm -q vsftpd &> /dev/null ;then
    echo "vsftpd已安装."
else
    yum -y install vsftpd &> /dev/null
fi
systemctl restart vsftpd

案例11:监控网络流量

[root@master shell]# cat net.sh
#!/bin/bash
while :
do
          clear
          echo  '本地网卡ens33流量信息如下: '
          ifconfig ens33 | grep "RX pack" | tr -s " " | cut -d" " -f6
          ifconfig ens33 | grep "TX pack" | tr -s " " | cut -d" " -f6
          sleep 1
done

案例12:统计闰年

[root@master shell]# cat leap.sh
#!/bin/bash
#功能描述(Description):判断有序的数字是否为闰年
#条件1:能被4整除但不能被100整除)条件2:能被400整除
#满足条件1或条件2之一就是闰年
for i in {1..5000}
do
    if [[ $[i%4] -eq 0 && $[i%100] -ne 0 || $[i%400] -eq 0 ]];then
        echo "$i:是闰年"
    else
        echo "$i:非闰年"
    fi
done

案例13:计算等差数列之和

[root@master shell]# cat sum.sh
#!/bin/bash
#功能描述(Description):计算等差数列之和1+2+3+,...,+100

sum=0;i=1
while [ $i -le 100 ]
do
    let sum+=$i
    let i++
done
echo -e "1+2+3+,...,+100的总和为:\033[1;32m$sum\033[0m"

案例14:判断用户输入

[root@master shell]# cat case1.sh
#!/bin/bash
read -p "请输入redhat|fedora:" key
case $key in
redhat)
    echo "fedora.";;
fedora)
    echo "redhat.";;
*)
    echo "必须输入redhat或fedora."
esac


[root@master shell]# cat case2.sh
#!/bin/bash
read -p  "Are you sure?[y/n]:"  sure
case  $sure  in
y|Y|yes|YES)
   echo "you enter $sure,OK";;
n|N|NO|no)
   echo "you enter $sure,OVER";;
*)
   echo "error";;
esac

案例15:倒计时脚本

[root@kube-node1 ~]# cat clock倒计时.sh
#!/bin/bash
#功能描述(Description):通过tput定位光标,在屏幕特定位置打印当前的计算机时间.

#使用Ctrl+C中断脚本时显示光标.
trap 'tput cnorm;exit' INT EXIT

#定义数组变量,该数字有9个元素,每行是1个元素,每一个数字占用12列.
#0的数组坐标位置为0-11,1的数组坐标位置为12-23,依此类推.
number=(
'  0000000000      111     2222222222  3333333333 44    44     5555555555  6666666666   777777777   888888888  9999999999 '
'  00      00    11111             22          33 44    44     55          66           77     77   88     88  99      99 '
'  00      00   111111             22          33 44    44     55          66           77     77   88     88  99      99 '
'  00      00       11             22          33 44    44     55          66                  77   88     88  99      99 '
'  00      00       11     2222222222  3333333333 44444444444  5555555555  6666666666          77   888888888  9999999999 '
'  00      00       11     22                  33       44             55  66      66          77   88     88          99 '
'  00      00       11     22                  33       44             55  66      66          77   88     88          99 '
'  00      00       11     22                  33       44             55  66      66          77   88     88          99 '
'  0000000000  1111111111  2222222222  3333333333       44      555555555  6666666666          77   888888888  9999999999 '
)

#获取计算机时间,并分别提取个位和十位数字.
get_time(){
   if [ -z "$1" ];then
       echo "Usage:$0 倒计时分钟"
       exit
   fi
   sec=$[$1*60]
}

#将数组中的某个数组打印出来.
print_time(){
    #从第几个位置开始提取数组元素,0就从0开始,1就从12开始,2就从24开始,依此类推.
    begin=$[$1*12]
    for i in `seq 0 ${#number[@]}`   #0-9的循环.
    do
        tput cup $[i+5] $2
        echo -en "\033[91m${number[i]:$begin:12}\033[0m"
    done
}

#依次打印小时,分钟,秒(个位和十位分别打印).
get_time $1
while :
do
    [ $sec -lt 0 ] && exit
    tput civis    #隐藏光标.
    tput clear
    tput cup 3 16
    echo  "倒计时:"
    for j in `seq ${#sec}`
    do
        num=`echo $sec | cut -c $j`
        y=$[j*16]
        print_time $num $y
    done
    let sec--
    echo
    sleep 1
done

案例16:贪吃蛇

[root@kube-node1 ~]# cat snake.sh
#!/bin/bash

declare -i x=5
declare -i y=5
declare -i len=4

declare -i x_arr=(1 2 3 4 5)
declare -i y_arr=(5 5 5 5 5)

declare -i res=0

dir='d'
level_arr=(0.3 0.2 0.1 0.01 0.005)

init() {
        clear
        echo -e "\033[0m"
        echo -e "\033[?25l"
        gen_food
}

set_show() {
                # \33[y;xH设置光标位置
        for ((i = 1; i < $len; i++)); do
                        echo -e "\033[47m\033[36m"
                        echo -e "\033[${y_arr[$i]};${x_arr[$i]}H*\033[0m"
        done
                echo -e "\033[42m\033[37"
                echo -e "\033[${y_arr[$i]};${x_arr[$i]}H+\033[0m"

                echo -e "\033[${randomy};${randomx}H$\033[0m"

                for ((i = 0; i <= 60; i++)); do
                        echo -e "\033[27;${i}H#\033[0m"
                        echo -e "\033[0;${i}H#\033[0m"
                done

                for ((i = 0; i <= 27; i++)); do
                        echo -e "\033[${i};0H#\033[0m"
                        echo -e "\033[${i};60H#\033[0m"
                done

                echo -e "\033[16;65Hsnake:${x},${y}\033[0m"
                echo -e "\033[17;65Hfood :${randomx},${randomy}\033[0m"
                echo -e "\033[28;0H\033[43mscore:${res}\033[0m"
}

move() {
        case $dir in
                        "w") y=$y-1 ;;
                        "s") y=$y+1 ;;
                        "a") x=$x-1 ;;
                        *) x=$x+1 ;;
                        "q") ret ;;
                esac
                # 吃到食物
                if [[ $x -eq $randomx && $y -eq $randomy ]]; then
                        ((len++))
                        ((res++));
                        x_arr[$len]=$x
                        y_arr[$len]=$y
                        gen_food
                        return
                fi

                if [[ $x -le 1 || $y -le 1 || $x -ge 60 || $y -ge 27 ]]; then
                        echo "出范围"
                        ret;
                fi

                for ((i = 2; i <= $len; i++)); do
                if [[ $x -eq ${x_arr[$i]} && $y -eq ${y_arr[$i]} ]]; then
                                        echo "吃到自己"
                        ret;
                fi
        done

        for ((i = 0; i <= $len; i++)); do
                x_arr[$i]=${x_arr[$i+1]}
                y_arr[$i]=${y_arr[$i+1]}
        done
                echo -e "\033[${y_arr[0]};${x_arr[0]}H\033[40m \033[0m"
        x_arr[$len]=$x
        y_arr[$len]=$y
}

gen_food() {
        let flag=1
        while [ $flag -eq 1 ]; do
                let randomx=$(($RANDOM%57+2))
                let randomy=$(($RANDOM%24+2))
                # 判断食物是否在蛇身
                for ((i=0;i<len;i++)); do
                        if [[ ${x_arr[$i]} -eq $randomx && ${y_arr[$i]} -eq $randomy ]]; then
                                break
                        fi
                done
                if [ $i -eq $len ]; then
                        flag=0
                fi
        done
}

ret() {
        echo -e "\033[0m"
        echo -e "\033[?25h"
        exit
}

init
set_show
while :; do
    olddir=$dir
        if [ $res -lt 5 ]; then
                level=0
        elif [ $res -lt 10 ]; then
                level=1
        elif [ $res -lt 15 ]; then
                level=2
        elif [ $res -lt 20 ]; then
                level=3
        elif [ $res -lt 25 ]; then
                level=4
        fi
    if ! read -n 1 -t ${level_arr[level]} -s dir; then
            dir=$olddir
    fi

        # 不能180反向
        if [[ $dir = "w" && $olddir = "s" ]]; then
                                dir=$olddir
        fi
        if [[ $dir = "s" && $olddir = "w" ]]; then
                                dir=$olddir
        fi
        if [[ $dir = "a" && $olddir = "d" ]]; then
                                dir=$olddir
        fi
        if [[ $dir = "d" && $olddir = "a" ]]; then
                                dir=$olddir
        fi

    move
    set_show
done

案例17:俄罗斯方块

[root@kube-node1 ~]# cat 俄罗斯方块.sh
#!/bin/bash

APP_NAME="${0##*[\\/]}"
APP_VERSION="1.0"

#颜色定义
iSumColor=7                     #颜色总数
cRed=1                          #红色
cGreen=2                        #绿色
cYellow=3                       #黄色
cBlue=4                         #蓝色
cFuchsia=5                      #紫红色
cCyan=6                         #青色(蓝绿色)
cWhite=7                        #白色

#位置与大小
marginLeft=3                    #边框左边距
marginTop=2                     #边框上边距
((mapLeft=marginLeft+2))        #棋盘左边距
((mapTop=$marginTop+1))         #棋盘上边距
mapWidth=10                     #棋盘宽度
mapHeight=15                    #棋盘高度

#颜色设置
cBorder=$cGreen
cScore=$cFuchsia
cScoreValue=$cCyan

#控制信号
#游戏使用两个进程,一个用于接收输入,一个用于游戏流程和显示界面;
#当前者接收到上下左右等按键时,通过向后者发送signal的方式通知后者。
sigRotate=25            #向上键
sigLeft=26
sigRight=27
sigDown=28
sigAllDown=29           #空格键
sigExit=30

#方块定义,7大类19种样式
#前8位为方块坐标,后2位为方块刚出现的时候的位置
box0_0=(0 0 0 1 1 0 1 1 0 4)

box1_0=(0 1 1 1 2 1 3 1 0 3)
box1_1=(1 0 1 1 1 2 1 3 -1 3)

box2_0=(0 0 1 0 1 1 2 1 0 4)
box2_1=(0 1 0 2 1 0 1 1 0 3)

box3_0=(0 1 1 0 1 1 2 0 0 4)
box3_1=(0 0 0 1 1 1 1 2 0 4)

box4_0=(0 2 1 0 1 1 1 2 0 3)
box4_1=(0 1 1 1 2 1 2 2 0 3)
box4_2=(1 0 1 1 1 2 2 0 -1 3)
box4_3=(0 0 0 1 1 1 2 1 0 4)

box5_0=(0 0 1 0 1 1 1 2 0 3)
box5_1=(0 1 0 2 1 1 2 1 0 3)
box5_2=(1 0 1 1 1 2 2 2 -1 3)
box5_3=(0 1 1 1 2 0 2 1 0 4)

box6_0=(0 1 1 0 1 1 1 2 0 3)
box6_1=(0 1 1 1 1 2 2 1 0 3)
box6_2=(1 0 1 1 1 2 2 1 -1 3)
box6_3=(0 1 1 0 1 1 2 1 0 4)

iSumType=7                      #方块类型总数
boxStyle=(1 2 2 2 4 4 4)        #各种方块旋转后可能的样式数目

iScoreEachLevel=50      #提升一个级别需要的分数
#运行时数据
sig=0                   #接收到的signal
iScore=0                #总分
iLevel=0                #速度级
boxNext=()              #下一个方块
iboxNextColor=0         #下一个方块的颜色
iboxNextType=0          #下一个方块的种类
iboxNextStyle=0         #下一个方块的样式
boxCur=()               #当前方块的位置定义
iBoxCurColor=0          #当前方块的颜色
iBoxCurType=0           #当前方块的种类
iBoxCurStyle=0          #当前方块的样式
boxCurX=-1              #当前方块的x坐标位置
boxCurY=-1              #当前方块的y坐标位置
map=()                  #棋盘图表

#初始化所有背景方块为-1, 表示没有方块
for ((i = 0; i < mapHeight * mapWidth; i++))
do
        map[$i]=-1
done

#接收输入的进程的主函数
function RunAsKeyReceiver()
{
        local pidDisplayer key aKey sig cESC sTTY

        pidDisplayer=$1
        aKey=(0 0 0)

        cESC=`echo -ne "\033"`
        cSpace=`echo -ne "\040"`

        #保存终端属性。在read -s读取终端键时,终端的属性会被暂时改变。
        #如果在read -s时程序被不幸杀掉,可能会导致终端混乱,
        #需要在程序退出时恢复终端属性。
        sTTY=`stty -g`

        #捕捉退出信号
        trap "MyExit;" INT QUIT
        trap "MyExitNoSub;" $sigExit

        #隐藏光标
        echo -ne "\033[?25l"

        while :
        do
                #读取输入。注-s不回显,-n读到一个字符立即返回
                read -s -n 1 key

                aKey[0]=${aKey[1]}
                aKey[1]=${aKey[2]}
                aKey[2]=$key
                sig=0

                #判断输入了何种键
                if [[ $key == $cESC && ${aKey[1]} == $cESC ]]
                then
                        #ESC键
                        MyExit
                elif [[ ${aKey[0]} == $cESC && ${aKey[1]} == "[" ]]
                then
                        if [[ $key == "A" ]]; then sig=$sigRotate       #<向上键>
                        elif [[ $key == "B" ]]; then sig=$sigDown       #<向下键>
                        elif [[ $key == "D" ]]; then sig=$sigLeft       #<向左键>
                        elif [[ $key == "C" ]]; then sig=$sigRight      #<向右键>
                        fi
                elif [[ $key == "W" || $key == "w" ]]; then sig=$sigRotate      #W, w
                elif [[ $key == "S" || $key == "s" ]]; then sig=$sigDown        #S, s
                elif [[ $key == "A" || $key == "a" ]]; then sig=$sigLeft        #A, a
                elif [[ $key == "D" || $key == "d" ]]; then sig=$sigRight       #D, d
                elif [[ "[$key]" == "[]" ]]; then sig=$sigAllDown       #空格键
                elif [[ $key == "Q" || $key == "q" ]]                   #Q, q
                then
                        MyExit
                fi

                if [[ $sig != 0 ]]
                then
                        #向另一进程发送消息
                        kill -$sig $pidDisplayer
                fi
        done
}

#退出前的恢复
MyExitNoSub()
{
        local y

        #恢复终端属性
        stty $sTTY
        ((y = marginTop + mapHeight + 4))

        #显示光标
        echo -e "\033[?25h\033[${y};0H"
        exit
}

MyExit()
{
        #通知显示进程需要退出
        kill -$sigExit $pidDisplayer

        MyExitNoSub
}

#处理显示和游戏流程的主函数
RunAsDisplayer()
{
        local sigThis
        InitDraw

        #挂载各种信号的处理函数
        trap "sig=$sigRotate;" $sigRotate
        trap "sig=$sigLeft;" $sigLeft
        trap "sig=$sigRight;" $sigRight
        trap "sig=$sigDown;" $sigDown
        trap "sig=$sigAllDown;" $sigAllDown
        trap "ShowExit;" $sigExit

        while :
        do
                #根据当前的速度级iLevel不同,设定相应的循环的次数
                for ((i = 0; i < 21 - iLevel; i++))
                do
                        sleep 0.02
                        sigThis=$sig
                        sig=0

                        #根据sig变量判断是否接受到相应的信号
                        if ((sigThis == sigRotate)); then BoxRotate;    #旋转
                        elif ((sigThis == sigLeft)); then BoxLeft;      #左移一列
                        elif ((sigThis == sigRight)); then BoxRight;    #右移一列
                        elif ((sigThis == sigDown)); then BoxDown;      #下落一行
                        elif ((sigThis == sigAllDown)); then BoxAllDown;        #下落到底
                        fi
                done
                #kill -$sigDown $$
                BoxDown #下落一行
        done
}

#绘制当前方块,传第一个参数,0表示擦除当前方块,1表示绘制当前方块
DrawCurBox()
{
        local i x y bErase sBox
        bErase=$1
        if (( bErase == 0 ))
        then
                sBox="\040\040"         #用两个空格擦除
        else
                sBox="[]"
                echo -ne "\033[1m\033[3${iBoxCurColor}m\033[4${iBoxCurColor}m"
        fi

        for ((i = 0; i < 8; i += 2))
        do
                ((y = mapTop + 1 + ${boxCur[$i]} + boxCurY))
                ((x = mapLeft + 1 + 2 * (boxCurX + ${boxCur[$i + 1]})))
                echo -ne "\033[${y};${x}H${sBox}"
        done
        echo -ne "\033[0m"
}

#移动方块
#BoxMove(y, x), 测试是否可以把移动中的方块移到(y, x)的位置, 返回0则可以, 1不可以
BoxMove()
{
        local i x y xPos yPos
        yPos=$1
        xPos=$2
        for ((i = 0; i < 8; i += 2))
        do
                #方块相对于棋盘坐标
                ((y = yPos + ${boxCur[$i]}))
                ((x = xPos + ${boxCur[$i + 1]}))

                if (( y < 0 || y >= mapHeight || x < 0 || x >= mapWidth))
                then
                        #撞到墙壁了
                        return 1
                fi

                if (( ${map[y * mapWidth + x]} != -1 ))
                then
                        #撞到其他已经存在的方块了
                        return 1
                fi
        done
        return 0;
}

#将方块贴到棋盘上
Box2Map()
{
        local i j x y line
        #将当前移动中的方块贴到棋盘对应的区域
        for ((i = 0; i < 8; i += 2))
        do
                #计算方块相对于棋盘的坐标
                ((y = ${boxCur[$i]} + boxCurY))
                ((x = ${boxCur[$i + 1]} + boxCurX))
                map[y*mapWidth+x]=$iBoxCurColor #将方块颜色赋给地图
        done

        line=0
        for ((i = 0; i < mapHeight; i++))
        do
                for ((j = 0; j < mapWidth; j++))
                do
                        #如果棋盘上有空隙,跳出循环
                        [[ ${map[i*mapWidth+j]} -eq -1 ]] && break
                done

                [ $j -lt $mapWidth ] && continue
                #说明当前行可消去,可消去行数加一
                (( line++ ))

                #第i行可被消除,将0行至第i-1行全部下移一行,从第i-1行开始移动
                for ((j = i*mapWidth-1; j >= 0; j--))
                do
                        ((x = j + mapWidth))
                        map[$x]=${map[$j]}
                done

                #因为下移一行,第0行置空
                for ((i = 0; i < mapWidth; i++))
                do
                        map[$i]=-1
                done
        done

        [ $line -eq 0 ] && return

        #根据消去的行数line计算分数和速度级
        ((x = marginLeft + mapWidth * 2 + 7))
        ((y = marginTop + 11))
        ((iScore += line * 2 - 1))
        #显示新的分数
        echo -ne "\033[1m\033[3${cScoreValue}m\033[${y};${x}H${iScore}         "
        if ((iScore % iScoreEachLevel < line * 2 - 1))
        then
                if ((iLevel < 20))
                then
                        ((iLevel++))
                        ((y = marginTop + 14))
                        #显示新的速度级
                        echo -ne "\033[3${cScoreValue}m\033[${y};${x}H${iLevel}        "
                fi
        fi
        echo -ne "\033[0m"

        #重新显示背景方块
        for ((i = 0; i < mapHeight; i++))
        do
                #棋盘相对于屏幕的坐标
                ((y = i + mapTop + 1))
                ((x = mapLeft + 1))
                echo -ne "\033[${y};${x}H"
                for ((j = 0; j < mapWidth; j++))
                do
                        ((tmp = i * mapWidth + j))
                        if ((${map[$tmp]} == -1))
                        then
                                echo -ne "  "
                        else
                                echo -ne "\033[1m\033[3${map[$tmp]}m\033[4${map[$tmp]}m[]\033[0m"
                        fi
                done
        done
}

#左移一格
BoxLeft()
{
        local x
        ((x = boxCurX - 1))
        if BoxMove $boxCurY $x
        then
                DrawCurBox 0
                ((boxCurX = x))
                DrawCurBox 1
        fi
}

#右移一格
BoxRight()
{
        local x
        ((x = boxCurX + 1))
        if BoxMove $boxCurY $x
        then
                DrawCurBox 0
                ((boxCurX = x))
                DrawCurBox 1
        fi
}

#向下移一格
BoxDown()
{
        local y
        ((y = boxCurY + 1))     #新的y坐标
        if BoxMove $y $boxCurX  #测试是否可以下落一行
        then
                DrawCurBox 0    #将旧的方块抹去
                ((boxCurY = y))
                DrawCurBox 1    #显示新的下落后方块
        else
                #走到这儿, 如果不能下落了
                Box2Map         #将当前移动中的方块贴到背景方块中
                CreateBox       #产生新的方块
        fi
}

#下落到底
BoxAllDown()
{
        local y iDown

        #计算能够下落的行数
        iDown=0
        (( y = boxCurY + 1 ))
        while BoxMove $y $boxCurX
        do
                (( y++ ))
                (( iDown++ ))
        done

        DrawCurBox 0    #将旧的方块抹去
        ((boxCurY += iDown))
        DrawCurBox 1    #显示新的下落后的方块
        Box2Map         #将当前移动中的方块贴到背景方块中
        CreateBox       #产生新的方块
}

#翻转
BoxRotate()
{
        [ ${boxStyle[$iBoxCurType]} -eq 1 ] && return
        ((rotateStyle = (iBoxCurStyle + 1) % ${boxStyle[$iBoxCurType]}))
        #将当前方块保存到boxTmp
        boxTmp=( `eval 'echo ${boxCur[@]}'` )
        boxCur=( `eval 'echo ${box'$iBoxCurType'_'$rotateStyle'[@]}'` )

        if BoxMove $boxCurY $boxCurX    #测试旋转后是否有空间放的下
        then
                #抹去旧的方块
                boxCur=( `eval 'echo ${boxTmp[@]}'` )
                DrawCurBox 0

                boxCur=( `eval 'echo ${box'$iBoxCurType'_'$rotateStyle'[@]}'` )
                DrawCurBox 1
                iBoxCurStyle=$rotateStyle
        else
                #不能旋转,还是继续使用老的样式
                boxCur=( `eval 'echo ${boxTmp[@]}'` )
        fi
}

#准备下一个方块
PrepareNextBox()
{
        local i x y
        #清除右边预显示的方块
        if (( ${#boxNext[@]} != 0 )); then
                for ((i = 0; i < 8; i += 2))
                do
                        ((y = marginTop + 1 + ${boxNext[$i]}))
                        ((x = marginLeft + 2 * mapWidth + 7 + 2 * ${boxNext[$i + 1]}))
                        echo -ne "\033[${y};${x}H\040\040"
                done
        fi

        #随机生成预显式方块
        (( iBoxNextType = RANDOM % iSumType ))
        (( iBoxNextStyle = RANDOM % ${boxStyle[$iBoxNextType]} ))
        (( iBoxNextColor = RANDOM % $iSumColor + 1 ))

        boxNext=( `eval 'echo ${box'$iBoxNextType'_'$iBoxNextStyle'[@]}'` )


        #显示右边预显示的方块
        echo -ne "\033[1m\033[3${iBoxNextColor}m\033[4${iBoxNextColor}m"
        for ((i = 0; i < 8; i += 2))
        do
                ((y = marginTop + 1 + ${boxNext[$i]}))
                ((x = marginLeft + 2 * mapWidth + 7 + 2 * ${boxNext[$i + 1]}))
                echo -ne "\033[${y};${x}H[]"
        done

        echo -ne "\033[0m"

}

#显示新方块
CreateBox()
{
        if (( ${#boxCur[@]} == 0 )); then
                #当前方块不存在
                (( iBoxCurType = RANDOM % iSumType ))
                (( iBoxCurStyle = RANDOM % ${boxStyle[$iBoxCurType]} ))
                (( iBoxCurColor = RANDOM % $iSumColor + 1 ))
        else
                #当前方块已存在, 将下一个方块赋给当前方块
                iBoxCurType=$iBoxNextType;
                iBoxCurStyle=$iBoxNextStyle;
                iBoxCurColor=$iBoxNextColor
        fi

        #当前方块数组
        boxCur=( `eval 'echo ${box'$iBoxCurType'_'$iBoxCurStyle'[@]}'` )
        #初始化方块起始坐标
        boxCurY=boxCur[8];
        boxCurX=boxCur[9];

        DrawCurBox 1            #绘制当前方块
        if ! BoxMove $boxCurY $boxCurX
        then
                kill -$sigExit $PPID
                ShowExit
        fi

        PrepareNextBox

}

#绘制边框
DrawBorder()
{
        clear

        local i y x1 x2
        #显示边框
        echo -ne "\033[1m\033[3${cBorder}m\033[4${cBorder}m"

        ((x1 = marginLeft + 1))                         #左边框x坐标
        ((x2 = x1 + 2 + mapWidth * 2))                  #右边框x坐标
        for ((i = 0; i < mapHeight; i++))
        do
                ((y = i + marginTop + 2))
                echo -ne "\033[${y};${x1}H||"           #绘制左边框
                echo -ne "\033[${y};${x2}H||"           #绘制右边框
        done

        ((x1 = marginTop + mapHeight + 2))
        for ((i = 0; i < mapWidth + 2; i++))
        do
                ((y = i * 2 + marginLeft + 1))
                echo -ne "\033[${mapTop};${y}H=="       #绘制上边框
                echo -ne "\033[${x1};${y}H=="           #绘制下边框
        done
        echo -ne "\033[0m"

        #显示"Score"和"Level"字样
        echo -ne "\033[1m"
        ((y = marginLeft + mapWidth * 2 + 7))
        ((x1 = marginTop + 10))
        echo -ne "\033[3${cScore}m\033[${x1};${y}HScore"
        ((x1 = marginTop + 11))
        echo -ne "\033[3${cScoreValue}m\033[${x1};${y}H${iScore}"
        ((x1 = marginTop + 13))
        echo -ne "\033[3${cScore}m\033[${x1};${y}HLevel"
        ((x1 = marginTop + 14))
        echo -ne "\033[3${cScoreValue}m\033[${x1};${y}H${iLevel}"
        echo -ne "\033[0m"
}

InitDraw()
{
        clear                   #清屏
        DrawBorder              #绘制边框
        CreateBox               #创建方块
}

#退出时显示GameOVer!
ShowExit()
{
        local y
        ((y = mapHeight + mapTop + 3))
        echo -e "\033[${y};1HGameOver!\033[0m"
        exit
}

#游戏主程序在这儿开始.
if [[ "$1" == "--version" ]]; then
        echo "$APP_NAME $APP_VERSION"
elif [[ "$1" == "--show" ]]; then
        #当发现具有参数--show时,运行显示函数
        RunAsDisplayer
else
        bash $0 --show& #以参数--show将本程序再运行一遍
        RunAsKeyReceiver $!     #以上一行产生的进程的进程号作为参数
fi


keytest.sh



#!/bin/bash

GetKey()
{
        aKey=(0 0 0) #定义一个数组来保存3个按键

        cESC=`echo -ne "\033"`
        cSpace=`echo -ne "\040"`

        while :
        do
                read -s -n 1 key  #读取一个字符,将读取到的字符保存在key中
                #echo $key
                #echo XXX

                aKey[0]=${aKey[1]} #第一个按键
                aKey[1]=${aKey[2]} #第二个按键
                aKey[2]=$key        #第三个按键

                if [[ $key == $cESC && ${aKey[1]} == $cESC ]]
                then
                        MyExit
                elif [[ ${aKey[0]} == $cESC && ${aKey[1]} == "[" ]]
                then
                        if [[ $key == "A" ]]; then echo KEYUP
                        elif [[ $key == "B" ]]; then echo KEYDOWN
                        elif [[ $key == "D" ]]; then echo KEYLEFT
                        elif [[ $key == "C" ]]; then echo KEYRIGHT
                        fi
                fi
        done
}

GetKey


draw.sh





#!/bin/bash

#位置与大小
marginLeft=8                    #边框左边距
marginTop=6                     #边框上边距
((mapLeft=marginLeft+2))        #棋盘左边距
((mapTop=$marginTop+1))         #棋盘上边距
mapWidth=10                     #棋盘宽度
mapHeight=15                    #棋盘高度


#方块定义,7大类19种样式
#前8位为方块坐标,后2位为方块刚出现的时候的位置
box0_0=(0 0 0 1 1 0 1 1 0 4)

box1_0=(0 1 1 1 2 1 3 1 0 3)
box1_1=(1 0 1 1 1 2 1 3 -1 3)

box2_0=(0 0 1 0 1 1 2 1 0 4)
box2_1=(0 1 0 2 1 0 1 1 0 3)

box3_0=(0 1 1 0 1 1 2 0 0 4)
box3_1=(0 0 0 1 1 1 1 2 0 4)

box4_0=(0 2 1 0 1 1 1 2 0 3)
box4_1=(0 1 1 1 2 1 2 2 0 3)
box4_2=(1 0 1 1 1 2 2 0 -1 3)
box4_3=(0 0 0 1 1 1 2 1 0 4)

box5_0=(0 0 1 0 1 1 1 2 0 3)
box5_1=(0 1 0 2 1 1 2 1 0 3)
box5_2=(1 0 1 1 1 2 2 2 -1 3)
box5_3=(0 1 1 1 2 0 2 1 0 4)

box6_0=(0 1 1 0 1 1 1 2 0 3)
box6_1=(0 1 1 1 1 2 2 1 0 3)
box6_2=(1 0 1 1 1 2 2 1 -1 3)
box6_3=(0 1 1 0 1 1 2 1 0 4)


#绘制边框
DrawBorder()
{
        clear

        local i y x1 x2
        #显示边框
        echo -ne "\033[1m\033[32m\033[42m"

        ((x1 = marginLeft + 1))                         #左边框x坐标
        ((x2 = x1 + 2 + mapWidth * 2))                  #右边框x坐标
        for ((i = 0; i < mapHeight; i++))
        do
                ((y = i + marginTop + 2))
                echo -ne "\033[${y};${x1}H||"           #绘制左边框
                echo -ne "\033[${y};${x2}H||"           #绘制右边框
        done

        ((x1 = marginTop + mapHeight + 2))
        for ((i = 0; i < mapWidth + 2; i++))
        do
                ((y = i * 2 + marginLeft + 1))
                echo -ne "\033[${mapTop};${y}H=="       #绘制上边框
                echo -ne "\033[${x1};${y}H=="           #绘制下边框
        done
        echo -ne "\033[0m"
}

DrawBox()
{
        local i x y xPos yPos
        yPos=${box0_0[8]}
        xPos=${box0_0[9]}
        echo -ne "\033[1m\033[35m\033[45m"
        for ((i = 0; i < 8; i += 2))
        do
                (( y = mapTop + 1 + ${box0_0[$i]} + yPos ))
                (( x = mapLeft + 1 + 2 * (${box0_0[$i + 1]} + xPos) ))
                echo -ne "\033[${y};${x}H[]"
        done
        echo -ne "\033[0m"
}

InitDraw()
{
        clear                   #清屏
        DrawBorder              #绘制边框
        DrawBox
        while :
        do
                sleep 1
        done
}

InitDraw

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: shell