LinuxCommandLinex -- [ 脚本 - 读取输入]

  • read
  • $ISF

read

read [options] [variable...]

options:

  • -p prompt 提示语句
  • -t timeout 超时
  • -s slient 不显示用户输入(用于输入密码)
  • -i 用于提供默认值,必须和 -e 一起使用
# 提供默认值 $USER
# 读取输入,保存到变量名 name
[admin@localhost ~]$ read -e -p "Your name: " -i $USER  name && echo $name
Your name: admin
admin

$ cat test-integer.sh
#!/bin/bash

read -p "Enter an integer: " num

# 判断是否整数
if [[ "$num" =~ -?[[:digit:]]+ ]]; then

# 判断正负
  if (( num > 0 )); then
    printf "%s is positive\n" $num
  elif (( num < 0 )); then
    printf  "%s is negative\n" $num
  else
    printf "%s is zero\n" $num
  fi

# 判断奇偶
  if (( num % 2 == 0 )); then
    printf "%s is even\n" $num
  else
    printf "%s is odd\n" $num
  fi

# 不是整数,重定向到 stderr
else
  echo "$num is not an integer" >&2
  exit 1
fi

IFS

环境变量 IFS (internal field separator): 默认值是空白字符;
作用:作为 read 的分隔符

$ ./user_info.sh
Enter a username: admin

username: admin
group: admin
uid: 1000
gid: 1000
home: /home/admin:/bin/bash

$ cat ./user_info.sh
#!/bin/bash

# root:x:0:0:root:/root:/bin/bash

read -p "Enter a username: " -ei $USER user

user_info=$(grep "^$user" /etc/passwd)

if [ -n "$user_info" ]; then
    # 临时改变分隔符为 :
    # 用 <<< 将变量 user_info 的值作为标准输入传给 read
    IFS=":" read username passwd uid gid group home <<< "$user_info"
    printf "\nusername: %s" $username
    printf "\ngroup: %s" $group
    printf "\nuid: %s" $uid
    printf "\ngid: %s" $gid
    printf "\nhome: %s" $home
    printf "\n\n"
else
    echo "No such user: $user">&2
    exit 1
fi

操作符 >>>

>>> 用于重定向字符串
command1 | command2:管道将 command1 的输出作为 command2 的输输入,但是管道会创建一个 subshell (复制 command1 的环境变量) 来执行 comand2command2 执行完毕后销毁 subshell (清除环境变量)

# $variable 的值为空
$ echo "Hello" | read variable; echo $variable

# $variable 的值为 "Hello"
$ read variable <<< "Hello"; echo $variable
Hello
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 官网 中文版本 好的网站 Content-type: text/htmlBASH Section: User ...
    不排版阅读 9,938评论 0 5
  • .bat脚本基本命令语法 目录 批处理的常见命令(未列举的命令还比较多,请查阅帮助信息) 1、REM 和 :: 2...
    庆庆庆庆庆阅读 12,549评论 1 19
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,293评论 19 139
  • 基础命令 主要的命令和快捷键 Linux系统命令由三部分组成:cmd + [options]+[operation...
    485b1aca799e阅读 4,771评论 0 0
  • 姓名:袁永辉 学号:17101223423 转载自:http://mp.weixin.qq.com/s/85...
    AliY520阅读 5,374评论 0 0