基于linux下的shell运算及应用实例
程序员文章站
2022-07-05 20:02:13
...
shell 运算
运算符号 | 意义 |
---|---|
+,- | 加法,减法 |
*,/,% | 乘法,除法,取余 |
** | 幂运算 |
++,– | 自增,自减 |
<,<=,>,>= | 比较符号 |
=,+=,-=,*=,/=,%= | 赋值运算 例如a+=1相当于a=a+1 |
运算操作与运算命令 | 意义 |
---|---|
(()) | 用与整数运算 直接在shell用 |
let | 用于整数运算,与(())类似 |
expr | 用于整数运算,功能相对较多 |
bc | linux下的计算器,适合整数及小数运算 |
$[] | 用户整数运算 |
${} | 声明变量 |
示例 1:
用运算和已经学过的shell语句写一个10秒倒计时的脚本; |
[aaa@qq.com mnt]# vim coutdown.sh
#!/bin/bash
for ((NUM=10;NUM>0;NUM--))
do
echo -n " TIME $NUM "
echo -ne "\r \r"
sleep 1
done
示例 2:
用运算和已经学过的shell语句写一个1分10秒倒计时的脚本; |
#!/bin/bash
read -p "please input the minute: " m
read -p "please input the second: " s
i=$[m*60+s]
for ((p=$i;p>0;p--))
do
A=$[$p/60]
B=$[$p%60]
echo -ne "\033[31mTHE TIME \033[0m"
echo -n "$A:$B "
echo -ne "\r \r"
sleep 1
done
示例 3:
制作一个简易的运算器;
执行Calculator.sh 请输入要操作的数: 请输入要操作的运算: 清输入要操作的第二个数: 显示操作后的数值: |
#!/bin/bash
read -p "Please input first number: " NUM_1
read -p "please input the action: " ACTION
read -p "please input second number: " NUM_2
bc <<EOF
$NUM_1 $ACTION $NUM_2
EOF
实例
实例 1:
输出 1-10,但不显示4 |
[aaa@qq.com mnt]# vim /mnt/test.sh
#!/bin/bash
for NUM in {1..10}
do
while [ "$NUM" -ne "4" ]
do
echo $NUM
break
done
done
实例 2:
编写一个脚本,完成以下功能: 完成指定远程主机新建用户,用户存在于文件/mnt/userfile,密码为/mnt/passfile; 例如:sh create_user.sh userfile passfile 5 9 //在ip主机号为5-9的5台主机上创建文件中存在的用户; |
vim /mnt/create_user.sh
#!/bin/bash
AUTO_CONNECT()
{
/usr/bin/expect << EOF
spawn ssh aaa@qq.com172.25.254.$1 $2
expect {
"yes/no" { send "yes\r";exp_continue }
"password" { send "westos\r" }
}
expect eof
EOF
}
for IP in {$3,$4}
do
ping -c1 -w1 172.25.254.$IP &> /dev/null && {
MAX_NUM=`awk 'BEGIN{N=0}{N++}END{print N}' $1`
for LINE_NUM in `seq 1 $MAX_NUM`
do
USERNAME=`sed -n "${LINE_NUM}p" $1`
PASSWORD=`sed -n "${LINE_NUM}p" $2`
AUTO_CONNECT $IP "useradd $USERNAME"
[ "$?" -eq "0" ]&&{
AUTO_CONNECT $IP "echo $PASSWORD | passwd --stdin $USERNAME"
}
done
}||{
echo -e "\033[32m172.25.254.$IP is down!!\033[0m"
}
done
实例 3:
数据库备份:执行db_dump.sh westos(数据库密码) 脚本执行后会备份数据库中所有库到/mnt/mysqldump目录中 备份文件名称为“库名称.sql”,当此文件存在时报错并询问动作, 输入“S”跳过备份,当输入“B”时,备份“库名称.sql”文件为“库名称_backup,sql”,当输入“O”时,覆盖原文件; |
#!/bin/bash
mkdir -p /mnt/mysqldump
DATABASE=`mysql -uroot -pwestos -EN -e "show databases;" | grep -v -E "^\*|schema$" `
for MYSQL_NAME in $DATABASE
do
if
[ -e /mnt/mysqldump/${MYSQL_NAME}.sql ]
then
read -p "$MYSQL_NAME has been dumped!
[S]kip [B]ackup [O]verwrite [E]xit
please input the action: " ACTION
ACTION=`echo $ACTION|tr 'A-Z' 'a-z'`
case $ACTION in
s)
;;
b)
mysqldump -uroot -p$1 $MYSQL_NAME > /mnt/mysqldump/${MYSQL_NAME}_backup.sql
;;
o)
mysqldump -uroot -p$1 $MYSQL_NAME > /mnt/mysqldump/${MYSQL_NAME}.sql
;;
e)
echo -e "\033[33mbye\033[0m"
exit
esac
else
mysqldump -uroot -p$1 $MYSQL_NAME > /mnt/mysqldump/${MYSQL_NAME}.sql
echo -e "\033[33m$MYSQL_NAME is backuped!\033[0m"
fi
done
下一篇: linux下shell脚本编写