Linux下脚本中的运算和shell脚本实例
程序员文章站
2022-07-05 20:02:43
...
实验1:显示10s倒计时
[aaa@qq.com mnt]# vim time.sh
#!/bin/bash
for ((num=10;num>0;num--))
do
echo -n " Time $num "
echo -ne "\r \r"
sleep 1
done
#测试:
实验2:显示1分10s倒计时
[aaa@qq.com mnt]# vim time1.sh
#!/bin/bash
for ((time=70;time>0;time--))
do
m=$[time/60]
s=$[time%60]
echo -n " Time $m:$s "
echo -ne "\r \r"
sleep 1
done
#测试:
实验3:编写一个脚本,实现计算器的功能
[aaa@qq.com mnt]# vim calculator.sh
#!/bin/bash
read -p "Please input first number: " num1
read -p "Please input act you want to do: " sgin
read -p "Please input second number: " num2
bc <<EOF
$num1$sgin$num2
EOF
#测试:
实验4:在其他主机上批量建立用户
[aaa@qq.com mnt]# vim user_create.sh
#!/bin/bash
Auto_Connect()
{
/usr/bin/expect << EOF|grep -E "authenticity|fingerprint|connecting|Warning|spawn|password" -v
set timeout 10
spawn ssh aaa@qq.com172.25.254.$IP "$1"
expect {
"yes/no" { send "yes\r";exp_continue }
"password" {send "westos\r" }
}
expect eof
EOF
}
for IP in 167
do
ping -c1 -w1 172.25.254.$IP &> /dev/null &&{
MAX_LINE=`awk 'BEGIN{N=0}{N++}END{print N}' $1`
for LINE_NUM in `seq 1 $MAX_LINE`
do
USERNAME=`sed -n "${LINE_NUM}p" $1`
PASSWORD=`sed -n "${LINE_NUM}p" $2`
User_check=`Auto_Connect "useradd $USERNAME"`
[ -n "$User_check" ] &&{
echo $User_check
} ||{
Auto_Connect "echo $PASSWORD|passwd --stdin $USERNAME"
}
done
}|| echo 172.25.254.$IP is down
done
#测试:
实验5:数据库的备份,执行脚本备份数据库里所有库到/mnt/mysqldump,备份文件名为“库名称.sql”,当此文件存在时报错并询问动作,输入“S”跳过,“B”备份为“库名称_backup.sql”,输入“O”,覆盖源文件
[aaa@qq.com mnt]# vim database.sh
#!/bin/bash
DATABASE=`mysql -uroot -pwestos -EN -e "show databases;"|grep -E "^\*|schema$" -v`
mkdir -p /mnt/mysqldump
for DATABASE in $DATABASE
do
if [ -e /mnt/mysqldump/${DATABASE}.sql ]
then
read -p "$DATABASE has been dumped!
[S]kip [B]ackup [O]verwrite
Please input action: " ACT
case $ACT in
S)
;;
B)
mysqldump -uroot -pwestos $DATABASE > /mnt/mysqldump/${DATABASE}_backup.sql
;;
O)
mysqldump -uroot -pwestos $DATABASE > /mnt/mysqldump/${DATABASE}.sql
;;
esac
else
mysqldump -uroot -pwestos $DATABASE > /mnt/mysqldump/${DATABASE}.sql
echo $DATABASE is backuped!
fi
done