Liunx shell的学习

Shell简单例子

  • 查看当前工作路径并列出当前所有的文件和属性
[xiao@yang play]$ touch example.sh
[xiao@yang play]$ vim example.sh
[xiao@yang play]$ bash example.sh
/home/xiao/Desktop/play
total 8
drwxr-xr-x. 2 xiao xiao 42 Jan 11 10:49 .
drwxr-xr-x. 5 xiao xiao 54 Jan 11 10:41 ..
-rw-rw-r--. 1 xiao xiao 44 Jan 11 10:49 example.sh
-rw-rw-r--. 1 xiao xiao 31 Jan 12  2020 practice.txt
[xiao@yang play]$

example.sh

#/bin/bash
# For example By Yang
pwd
ls -al
  • 用户输入
[xiao@yang play]$ vim example.sh
[xiao@yang play]$ bash example.sh one two three four five
脚本名称example.sh
总共有5个参赛,分别是one two three four five
第一个参数是one

example.sh

#/bin/bash
# For example By Yang
echo "脚本名称$0"
echo "总共有$#个参赛,分别是$*"
echo "第一个参数是$1“
  • 判断文件
[xiao@yang play]$ [ -d /a ]
[xiao@yang play]$ echo $?
1

  • 数字
[xiao@yang play]$ [ 8 -eq 9 ]
[xiao@yang play]$ echo $?
1
[xiao@yang play]$ [ 8 -eq 8 ]
[xiao@yang play]$ echo $?
0
[xiao@yang play]$
  • if,判断文件是否存在,不存在就创建
[xiao@yang play]$ touch mkchrom.sh
[xiao@yang play]$ vim mkchrom.sh
[xiao@yang play]$ bash mkchrom.sh
[xiao@yang play]$ ls
example.sh  mkchrom.sh  practice.txt  yang
[xiao@yang play]$ cat mkchrom.sh
#!/bin/bash
DIR="yang"
if [ ! -e $DIR ]
then
mkdir -p $DIR
fi

  • fi 输入分数,判断是否优秀
[xiao@yang play]$ vim chkscore.sh
[xiao@yang play]$ bash chkscore.sh
Enter your score(0-100):88
88 is Excellent
[xiao@yang play]$ bash chkscore.sh
Enter your score(0-100):33
33 is Fail
[xiao@yang play]$ cat chkscore.sh
#!/bin/bash
read -p "Enter your score(0-100):" GRADE
if [ $GRADE -ge 85 ] && [ $GRADE -le 100 ]
then
echo "$GRADE is Excellent"
elif [ $GRADE -ge 70 ] && [ $GRADE -le 84 ]
then
echo "$GRADE is Pass"
else
echo "$GRADE is Fail"
fi
[xiao@yang play]$ 

  • while循环,猜价格
[xiao@yang play]$ touch Guess.sh
[xiao@yang play]$ vim Guess.sh
[xiao@yang play]$ bash Guess.sh
商品实际价格在0到99内
请输入猜测的价格:50
太高了!
请输入猜测的价格:30
太低了!
请输入猜测的价格:40
太低了!
请输入猜测的价格:45
太高了!
请输入猜测的价格:43
太低了!
请输入猜测的价格:44
恭喜答对了,实际价格是:44
您猜测了6次[xiao@yang play]$ cat Guess.sh
#!/bin/bash
PRICE=$(expr $RANDOM % 100)
TIMES=0
echo "商品实际价格在0到99内"
while true
do 
read -p "请输入猜测的价格:" INT
let TIMES++
if [ $INT -eq $PRICE ]
then
echo "恭喜答对了,实际价格是:$PRICE"
echo "您猜测了$TIMES次"
exit 0
elif [ $INT -gt $PRICE ]
then
echo "太高了!"
else
echo "太低了!"
fi
done
  • case猜测用户输入的内容
[xiao@yang play]$ touch checkkeys.sh
[xiao@yang play]$ vim checkkeys.sh
[xiao@yang play]$ bash checkkeys.sh
请输入一个字符a
您输入的是字母
[xiao@yang play]$ bash checkkeys.sh
请输入一个字符8
您输入的是数字
[xiao@yang play]$ bash checkkeys.sh
请输入一个字符 
您输入的是控制字符
[xiao@yang play]$ cat checkkeys.sh
#!/bin/bash
read -p "请输入一个字符" KEY
case "$KEY" in [a-z]|[A-Z])
echo "您输入的是字母"
;;
[0-9])
echo "您输入的是数字"
;;
*)
echo "您输入的是控制字符"
esac

上一篇:Java学习的第二十四天:SSM框架


下一篇:爬虫爬取糗事百科段子