Linux基礎學習之Shell基礎——Bash變數——預定義變數
阿新 • • 發佈:2018-12-23
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隱藏選項,所以年齡輸入時會看不到內容
對於性別處,輸入一個字元,無論是什麼都會直接自動執行下一步,甚至不需要回車