shell靠谱判断条件写法,以及获取当前运行脚本绝对路径和名称方法

Shell靠谱判断条件写法


 

判断一个用户是否是root用户,简单判断是

#!/bin/bash
ROOT_UID=0
if ["$UID" -ne "$ROOT_UID" ]
then
    echo "you are not root.  "
fi

 

然而,在bash下,$UID是可以正确获取到值,但是在dash环境下,$UID获取到的是空值,此时会报错。

[: -ne: unexpected operator  (记住这个错误

kylin@host-172-17-65-70:~/qsruan/db$ ls -alh /bin/sh
lrwxrwxrwx 1 root root 4 3月   2  2016 /bin/sh -> dash
kylin@host-172-17-65-70:~/qsruan/db$ cat test.sh 
#!/bin/bash
$ROOT_UID=0
if [ $UID -ne $ROOT_UID ] then echo "you are not root. " fi kylin@host-172-17-65-70:~/qsruan/db$ sh test.sh test.sh: 2: [: -ne: unexpected operator kylin@host-172-17-65-70:~/qsruan/db$

在判断时,靠谱写法如下,可以有效防止空值:

#!/bin/bash
$ROOT_UID=0
if [ "$UID"x != "$ROOT_UID"x ]
then
    echo "you are not root.  "
fi

 


获取当前运行脚本绝对路径和名称

 


 

因为执行可能是当前目录 ./do.sh   也有可能是相对路径  ./script/do.sh  也有可能用sh各种情况

获取当前运行脚本绝对路径和名称的靠谱方法如下:

#!/bin/bash

echo `pwd`/$0

 

posted on 2018-03-13 18:55  mathore  阅读(452)  评论(0编辑  收藏  举报