1、預定義變量
預定義變量 | 作用 |
$? | 最後一次執行的指令的傳回狀态。如果這個變量的值為,證明上一個指令正确執行;如果這個變量的值為非0(具體是哪個數,由指令自己來決定),則證明上一個指令執行不正确了。 |
$$ | 目前程序的程序号(PID) |
$! | 背景運作的最後一個程序的程序号(PID) |
示例一、預定義變量$?的作用示例
[[email protected] ~]# ls
abc cde install.log sh 公共的 視訊 文檔 音樂
anaconda-ks.cfg cdef install.log.syslog testfile 模闆 圖檔 下載下傳 桌面
[[email protected] ~]# echo $?
0
[[email protected] ~]# lsgdds
-bash: lsgdds: command not found
[[email protected] ~]# echo $?
127
[[email protected] ~]# ls jigeang
ls: 無法通路jigeang: 沒有那個檔案或目錄
[[email protected] ~]# echo $?
2
另外,&& || 指令符号在使用時,歸根接地也是判斷了該預定義變量 $? ;
示例二、目前前台程序或者背景程序的程序号PID
[[email protected] ~]# echo $$
8053
[[email protected] ~]# echo $!
[[email protected] ~]#
示例三、
[[email protected] ~]# cd sh
[[email protected] sh]# ll
總用量 20
-rwxr-xr-x. 1 root root 45 12月 16 17:13 canshu1.sh
-rwxr-xr-x. 1 root root 327 12月 16 17:49 canshu4.sh
-rwxr-xr-x. 1 root root 97 12月 16 09:24 hello.sh
-rwxr-xr-x. 1 root root 114 12月 16 17:26 jiafajisuanqi.sh
-rwxr-xr-x. 1 root root 204 12月 16 17:36 shili3.sh
[[email protected] sh]# vim yudingyibianliang
#!/bin/bash
#Author:xiaoxiaozhou(E-mail:[email protected])
echo "The current process is $$"
#輸出目前程序的PID
#這個PID就是yudingyibianliang.sh這個腳本執行時,生成的PID
find /root -name hello.sh &
#使用find 指令在root目錄下查找的hello.sh檔案
#符号&的意思是把指令放入背景執行,工作管理我們在系統管理章節會詳細介紹
echo "The last one Daemon process is $! "
~
~
~
[[email protected] sh]# ./yudingyibianliang
The current process is 8215
The last one Daemon process is 8216
[[email protected] sh]# /root/sh/hello.sh
[[email protected] sh]#
2、接收鍵盤輸入
[[email protected] ~]# read 【選項】[變量]
選項:
-p "提示資訊” :在等待read輸入時,輸出提示資訊。
-t 秒數 :read指令會一直等待使用者輸入,使用此選項可以指定等待時間。
-n 字元數 :read指令之接收指定的字元數,就會執行。
-s :隐藏輸入的資料,适用于機密資訊的輸入。
[[email protected] sh]# vim canshu6.sh
#!/bin/bash
#Author:xiaoxiaozhou (E-mail:[email protected])
read -t 30 -p "Please input your name:" name
#提示“請輸入姓名” 并等待30秒,把使用者的輸入儲存入變量name中
echo "Name is $name"
read -s -t 30 -p "Please enter your age:" age
#年齡是隐私,是以我們用“-s" 選項隐藏輸入
echo "Age is $age "
echo -e "\n"
read -n 1 -t 30 -p "Please select your gender[M/F]: " gender
#使用“ -n 1 " 選項隻接收一個輸入字元就會執行(都不用輸入回車)
echo -e "\n"
echo "Sex is $gender "
~
~
~
[[email protected] sh]#
[[email protected] sh]# chmod 765 canshu6.sh
[[email protected] sh]# ./canshu6.sh
Please input your name:xiaoxiaozhou
Name is xiaoxiaozhou
Please enter your age:Age is 24224
Please select your gender[M/F]: F
Sex is F
[[email protected] sh]#
補充:如果在Linux中,輸入内容錯誤,想按 倒退鍵,需要同時按住Ctrl鍵才可。
如上,年齡在執行時,因為腳本中設定了-s隐藏選項,是以年齡輸入時會看不到内容
對于性别處,輸入一個字元,無論是什麼都會直接自動運作下一步,甚至不需要回車