read命令基础

shell除了可以直接赋值或脚本传参,还可以使用read命令从标准输入中获得,read为bash内置命令。

常用的参数:

  -p prompt:设置提示信息

  -t timeout:设置输入等待的时间,单位默认是秒


read的读入功能就相当于交互式接受用户输入,然后给变量赋值

在脚本中最直接的用法就是:

如:read -p -t  5 “pls input a num:”num


以read命令读入及传参的综合企业案例

第一关:要求输入两个不为空的值;

第二关:用户输入的均为整数,否则为game over;

#!/bin/bash
read -p "this is a num:" a
read -p "this is two num:" b

if [ -z "$a" -o -z "$b" ]; then
  echo "game over"
  exit 1
fi

expr $a + $b + 5 > /dev/null

if [ $? -eq 0 ]; then
  echo "good"
else
  echo "game over"
fi