【Shell脚本基础系列-8】用户交互

目录

  1. 入门
  2. if-else分支和for/while循环
  3. 环境变量
  4. 函数的使用
  5. 文件读写操作
  6. 睡眠
  7. 进程状态监测
  8. 用户交互

Interactive

Use read command to to get input from the user.

简单的示例

#!/usr/bin/env bash

read -p "What is your first name: " NAME
# -p: put the prompt on the same line as the user input

echo "Your name is: $NAME"

exit 0

校验用户输入

#!/usr/bin/env bash

VALID=0

while [ $VALID -eq 0 ]
do
    read -p "Please enter your name and age: " NAME AGE
    if [[ ( -z $NAME ) || ( -z $AGE ) ]] 
    then
        echo "Not enough parameters passed"
        continue
    elif [[ ! $NAME =~ ^[A-Za-z]+$ ]] 
    then
        echo "Non alpha characters detected [$NAME]"
        continue
    elif [[ ! $AGE =~ ^[0-9]+$ ]] 
    then
        echo "Non digit characters detected [$AGE]"
        continue
    fi
    VALID=1
done

echo "Name = $NAME, Age = $Age"

exit 0

猜数字游戏

#!/usr/bin/env bash

COMPUTER=$(($RANDOM%100))
WIN=0

while [ $WIN -eq 0 ]
do
    # read in the number
    read -p "Please enter your number (0-100): " NUMBER

    # validation
    if [ -z $NUMBER ] 
    then
        echo "Please enter one parameter"
        continue
    elif [[ ! $NUMBER =~ ^[0-9]+$ ]] 
    then
        echo "Non digit characters detected [$NUMBER]"
        continue
    elif [ $NUMBER -gt $COMPUTER ] 
    then
        echo "Enter a smaller number"
        continue
    elif [ $NUMBER -lt $COMPUTER ] 
    then
        echo "Enter a bigger number"
        continue
    fi
    WIN=1
done

echo "That's it! The number is $COMPUTER ."

exit 0


References

LinkedIn Learning: https://www.linkedin.com/learning/learning-linux-shell-scripting-2018

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值