1. 程式人生 > >unix中shell 非一般變數$0 $n $* [email protected] $! $?的詳解

unix中shell 非一般變數$0 $n $* [email protected] $! $?的詳解

$0:獲取當前執行指令碼的檔名,包括路徑。

[[email protected] script]# cat 0.sh
#!/bin/bash
echo $0
[[email protected] script]# sh 0.sh
0.sh
[[email protected] script]# cat 0.sh
#!/bin/bash
dirname "$0"
basename "$0"
[[email protected] script]# sh /byrd/script/0.sh
/byrd/script
0.sh

$n:獲取當前執行的shell指令碼的第N個引數,n=1..9,當n為0時表示指令碼的檔名,如果n大於9,用大括號括起來like${10}.

[[email protected] script]# cat n.sh
#!/bin/bash
echo $1 $2 ${10}
[[email protected] script]# sh n.sh a b c d e f g h i j k l m n
a b j
[[email protected] script]# sh n.sh {a..z}
a b j
[[email protected] script]# sh n.sh `seq 11`
1 2 10

$*:獲取當前shell的所有引數,將所有的命令列引數視為單個字串。
[email protected]

:這個程式的所有引數"$1" "$2" "$3" "...",這是將引數傳遞給其他程式的最佳方式,因此TA會保留所有內嵌在每個引數裡的任何空白。
$#:獲取當前shell命令列中引數的總個數。

[[email protected] script]# cat hashtag.sh
#!/bin/bash
echo "$#"
[[email protected] script]# sh hashtag.sh
0
[[email protected] script]# sh hashtag.sh 1 2 3
3
[[email protected] script]# sh hashtag.sh `seq 300`
300
[

[email protected] script]# cat example.sh
#!/bin/bash
#Example
if [ $# -ne 2 ];then
    echo "Error, please enter two parameters."
    exit 1
else
    echo "You did a good job."
fi
[[email protected] script]# sh example.sh a
Error, please enter two parameters.
[[email protected] script]# sh example.sh a b
You did a good job.
[[email protected] script]# sh example.sh a b c
Error, please enter two parameters.
$_:代表上一個命令的最後一個引數
$$:代表所在命令的PID

[[email protected] script]# cat dollar.sh
#!/bin/bash
echo "$$" >/tmp/dollar.pid
while true
do
    sleep 1
done
[[email protected] script]# sh dollar.sh
################################################
[[email protected] ~]# cat /tmp/dollar.pid
1483
[[email protected] ~]# ps -ef |grep 1483
root      1483  1453  0 14:58 pts/1    00:00:00 sh dollar.sh
root      1532  1483  0 14:58 pts/1    00:00:00 sleep 1
root      1534  1496  0 14:58 pts/0    00:00:00 grep 1483
[[email protected] ~]# ps -ef |grep dollar
root      1483  1453  0 14:58 pts/1    00:00:00 sh dollar.sh
root      1555  1496  0 14:58 pts/0    00:00:00 grep dollar

$!:代表最後執行的後臺命令的PID
$?:代表上一個命令執行是否成功的標誌,如果執行成功則$? 為0,否則不為0

[[email protected] script]$ pwd
/byrd/script
[[email protected] script]$ echo $?
0    #執行成功
[[email protected] script]$ ls /root
ls: cannot open directory /root: Permission denied
[[email protected] script]$ echo $?
2    #許可權拒絕
[[email protected] script]$ hahaha
-bash: hahaha: command not found
[[email protected] script]$ echo $?

127    #未找到該命令

###########################################
[[email protected] ~]$ cat /byrd/script/question_mark.sh
#!/bin/bash
#Example
ls -al /root >/dev/null 2>&1
if [ $? -eq 0 ];then
    echo "User is root"
else
    echo "The user is not root"
fi
[[email protected] script]# sh question_mark.sh
User is root
[[email protected] script]# su - byrd
[[email protected] ~]$ sh /byrd/script/question_mark.sh
The user is not root
未完成,待整理!

相關推薦

no