本文记录学习Linux Shell脚本的过程,有些脚本是参考大佬的教程,会在文章后面备注参考教程。
1. 模拟Linux 用户登录
#/bin/bash
echo -n "login:"
# 获取用户名
read name
echo -n "password:"
# 用户密码
read passwd
# 验证
if [ $name = "root" -a $passwd = "root" ]
then
echo "the host and password is right!"
else echo "input is error!"
fi
结果展示
2. 比较两个数的大小
#/bin/bash
echo "please enter two number"
read num1
read num2
# 也可以用[ ]比较
if test $num1 -eq $num2
then
echo "$num1 = $num2"
elif test $num1 -gt $num2
then
echo "$num1 >$num2"
else
echo "$num1 < $num2"
fi
结果展示
3. 查找某个文件目录下是否存在该文件
#/bin/bash
echo "enter a file name:"
read a
# 判断在root目录下是否含有该文件
if test -e /root/$a
then
echo "the file is exist!"
else
echo "the file is not exist!"
fi
结果展示
4. 判断当前用户是否正在使用(运行)
#/bin/bash
echo "Please enter a user:"
read user
# whoami命令行命令,当前用户是谁
# $()输出命令行命令的内容
b=$(whoami)
# [ ]
if test $user = $b
then
echo "the user is running."
else
echo "the user is not running."
fi
结果展示
5. 测试IP地址
#/bin/bash
for i in 1 2 3 4 5 6 7 8 9
do
echo "the number of $i computer is "
ping -c 1 192.168.0.$i
done
结果展示
6. 文件是否存在,不存在就新建
#/bin/bash
while :
do
echo "please input file's name:"
read a
if test -e /root/$a
then
echo "the file is existing Please input new file name:"
else
mkdir $a
echo "you aye sussesful!"
break
fi
done
结果展示
7. y/n 返回不同结果
#!/bin/bash
clear
echo "enter [y/n]:"
read a
case $a in
y|Y|Yes|YES) echo "you enter $a"
;;
n|N|NO|no) echo "you enter $a"
;;
*) echo "error"
;;
esac
结果展示
8. 内置命令的使用
$USER :当前用户
date :时间
who:显示当前登录系统的用户
uname -s :显示操作系统名称
#/bin/bash
clear
echo "Hello, $USER"
echo
echo "Today 's date id `date`"
echo
echo "the user is :"
who
echo
echo "this is `uname -s`"
echo
echo "that's all folks! "
结果展示
9. 现在距离国庆节还有多久天
#!/bin/bash
# 今天是366天中的哪一天
TODAY=`date +%j`
NATINALDAY=`date -d 1-Oct +%j` # Christmas day, in same format
echo "There are $(($NATIONALDAY - $TODAY)) days until National Day."
结果展示
10. 获取随机字符或数字
获取随机8位字符串
# 方法1:
echo $RANDOM |md5sum |cut -c 1-8
471b94f2
# 方法2:
openssl rand -base64 4
vg3BEg==
# 方法3:
cat /proc/sys/kernel/random/uuid |cut -c 1-8
ed9e032c
获取随机8位数字
# 方法1:
echo $RANDOM |cksum |cut -c 1-8
56648321
#方法2:
openssl rand -base64 4 |cksum |cut -c 1-8
78591131
#方法3:
date +%N |cut -c 1-8
20364815
参考文章
- https://www.jb51.net/article/54488.htm