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
總結
以上是生活随笔為你收集整理的linux脚本读取输入信息,LinuxCommandLinex -- [ 脚本 - 读取输入]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: u盘修复linux系统,360u盘修复工
- 下一篇: 怎么在linux下查看gpu版本号,li