linux脚本读取输入信息,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 的环境变量) 来执行 comand2,command2 执行完毕后销毁 subshell (清除环境变量)

# $variable 的值为空

$ echo "Hello" | read variable; echo $variable

# $variable 的值为 "Hello"

$ read variable <<< "Hello"; echo $variable

Hello

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值