Shell中判断语句if中-z至-d的意思 - sunny_2015 - 博客园 https://www.cnblogs.com/coffy/p/5748292.html

Conditions in bash scripting (if statements) - Linux Academy Blog https://linuxacademy.com/blog/linux/conditions-in-bash-scripting-if-statements/

Table of conditions

The following table list the condition possibilities for both the single- and the double-bracket syntax. Save a single exception, the examples are given in single-bracket syntax, but are always compatible with double brackets.

1. File-based conditions:

Condition True if Example/explanation
[ -a existingfile ] file ‘existingfile’ exists. if [ -a tmp.tmp ]; then
rm -f tmp.tmp # Make sure we’re not bothered by an old temporary file
fi
[ -b blockspecialfile ] file ‘blockspecialfile’ exists and is block special. Block special files are special kernel files found in /dev, mainly used for ATA devices like hard disks, cd-roms and floppy disks.

if [ -b /dev/fd0 ]; then
dd if=floppy.img of=/dev/fd0 # Write an image to a floppy
fi

[ -c characterspecialfile ] file ‘characterspecialfile’ exists and is character special. Character special files are special kernel files found in /dev, used for all kinds of purposes (audio hardware, tty’s, but also /dev/null).

if [ -c /dev/dsp ]; then
cat raw.wav > /dev/dsp # This actually works for certain raw wav files
fi

[ -d directory ] file ‘directory’ exists and is a directory. In UNIX-style, directories are a special kind of file.

if [ -d ~/.kde ]; then
echo “You seem to be a kde user.”
fi

[ -e existingfile ] file ‘existingfile’ exists. (same as -a, see that entry for an example)
[ -f regularfile ] file ‘regularfile’ exists and is a regular file. A regular file is neither a block or character special file nor a directory.

if [ -f ~/.bashrc ]; then
source ~/.bashrc
fi

[ -g sgidfile ] file ‘sgidfile’ exists and is set-group-ID. When the SGID-bit is set on a directory, all files created in that directory will inherit the group of the directory.

if [ -g . ]; then
echo “Created files are inheriting the group ‘$(ls -ld . | awk ‘{ print $4 }’)’ from the working directory.”
fi

[ -G fileownedbyeffectivegroup ] file ‘fileownedbyeffectivegroup’ exists and is owned by the effective group ID. The effective group id is the primary group id of the executing user.

if [ ! -G file ]; then # An exclamation mark inverts the outcome of the condition following it
chgrp $(id -g) file # Change the group if it’s not the effective one
fi

[ -h symboliclink ] file ‘symboliclink’ exists and is a symbolic link. if [ -h $pathtofile ]; then
pathtofile=$(readlink -e $pathtofile) # Make sure $pathtofile contains the actual file and not a symlink to it
fi
[ -k stickyfile ] file ‘stickyfile’ exists and has its sticky bit set. The sticky bit has got quite a history, but is now used to prevent world-writable directories from having their contents deletable by anyone.

if [ ! -k /tmp ]; then # An exclamation mark inverts the outcome of the condition following it
echo “Warning! Anyone can delete and/or rename your files in /tmp!”
fi

[ -L symboliclink ] file ‘symboliclink’ exists and is a symbolic link. (same as -h, see that entry for an example)
[ -N modifiedsincelastread ] file ‘modifiedsincelastread’ exists and was modified after the last read. if [ -N /etc/crontab ]; then
killall -HUP crond # SIGHUP makes crond reread all crontabs
fi
[ -O fileownedbyeffectiveuser ] file ‘fileownedbyeffectiveuser’ exists and is owned by the user executing the script. if [ -O file ]; then
chmod 600 file # Makes the file private, which is a bad idea if you don’t own it
fi
[ -p namedpipe ] file ‘namedpipe’ exists and is a named pipe. A named pipe is a file in /dev/fd/ that can be read just once. See my bash tutorial for a case in which it’s used.

if [ -p $file ]; then
cp $file tmp.tmp # Make sure we’ll be able to read
file=”tmp.tmp”    # the file as many times as we like
fi

[ -r readablefile ] file ‘readablefile’ exists and is readable to the script. if [-r file ]; then
content=$(cat file) # Set $content to the content of the file
fi
[ -s nonemptyfile ] file ‘nonemptyfile’ exists and has a size of more than 0 bytes. if [ -s logfile ]; then
gzip logfile    # Backup the old logfile
touch logfile # before creating a fresh one.
fi
[ -S socket ] file ‘socket’ exists and is a socket. A socket file is used for inter-process communication, and features an interface similar to a network connection.

if [ -S /var/lib/mysql/mysql.sock ]; then
mysql –socket=/var/lib/mysql/mysql.sock #See this MySQL tip
fi

[ -t openterminal ] file descriptor ‘openterminal’ exists and refers to an open terminal. Virtually everything is done using files on Linux/UNIX, and the terminal is no exception.

if [ -t /dev/pts/3 ]; then
echo -e “nHello there. Message from terminal $(tty) to you.” > /dev/pts/3 #Anyone using that terminal will actually see this message!
fi

[ -u suidfile ] file ‘suidfile’ exists and is set-user-ID. Setting the suid-bit on a file causes execution of that file to be done with the credentials of the owner of the file, not of the executing user.

if [ -u executable ]; then
echo “Running program executable as user $(ls -l executable | awk ‘{ print $3 }’).”
fi

[ -w writeablefile ] file ‘writeablefile’ exists and is writeable to the script. if [ -w /dev/hda ]; then
grub-install /dev/hda
fi
[ -x executablefile ] file ‘executablefile’ exists and is executable for the script. Note that the execute permission on a directory means that it’s searchable (you can see which files it contains).

if [ -x /root ]; then
echo “You can view the contents of the /root directory.”
fi

[ newerfile -nt olderfile ] file ‘newerfile’ was changed more recently than ‘olderfile’, or if ‘newerfile’ exists and ‘olderfile’ doesn’t. if [ story.txt1 -nt story.txt ]; then
echo “story.txt1 is newer than story.txt; I suggest continuing with the former.”
fi
[ olderfile -ot newerfile ] file ‘olderfile’ was changed longer ago than ‘newerfile’, or if ‘newerfile’ exists and ‘olderfile’ doesn’t. if [ /mnt/remote/remotefile -ot localfile ]; then
cp -f localfile /mnt/remote/remotefile # Make sure the remote location has the newest version of the file, too
fi
[ same -ef file ] file ‘same’ and file ‘file’ refer to the same device/inode number. if [ /dev/cdrom -ef /dev/dvd ]; then
echo “Your primary cd drive appears to read dvd’s, too.”
fi

2. String-based conditions:

Condition True if Example/explanation
[ STRING1 == STRING2 ] STRING1 is equal to STRING2. if [ “$1” == “moo” ]; then
echo $cow # Ever tried executing ‘apt-get moo’?
fiNote: you can also use a single “=” instead of a double one.
[ STRING1 != STRING2 ] STRING1 is not equal to STRING2. if [ “$userinput” != “$password” ]; then
echo “Access denied! Wrong password!”
exit 1 # Stops script execution right here
fi
[ STRING1 > STRING2 ] STRING1 sorts after STRING2 in the current locale (lexographically). The backslash before the angle bracket is there because the bracket needs to be escaped to be interpreted correctly. As an example we have a basic bubble sort:

(Don’t feel ashamed if you don’t understand this, it is a more complex example)

array=( linux tutorial blog )
swaps=1
while (( swaps > 0 )); do

swaps=0
for (( i=0; i < (( ${#array[@]} – 1 )) ; i++ )); do
if [ “${array[$i]}” > “${array[$(( i + 1 ))]}” ]; then # Here is the sorting condition
tempstring=${array[$i]}
array[$i]=${array[$(( i + 1 ))]}
array[$(( i + 1 ))]=$tempstring
(( swaps=swaps + 1 ))
fi
done
done
echo ${array[@]} # Returns “blog linux tutorial”

[ STRING1 < STRING2 ] STRING1 sorts before STRING2 in the current locale (lexographically).
[ -n NONEMPTYSTRING ] NONEMPTYSTRING has a length of more than zero. This condition only accepts valid strings, so be sure to quote anything you give to it.

if [ -n “$userinput” ]; then
userinput=parse($userinput) # Only parse if the user actually gave some input.
fi

Note that you can also omit the “-n”, as brackets with just a string in it behave the same.

[ -z EMPTYSTRING ] EMPTYSTRING is an empty string. This condition also accepts non-string input, like an uninitialized variable:

if [ -z $uninitializedvar ]; then
uninitializedvar=”initialized” # -z returns true on an uninitialized variable, so we initialize it here.
fi

Double-bracket syntax only:
[[ STRING1 =~ REGEXPATTERN ]]
STRING1 matches REGEXPATTERN. If you are familiar with Regular Expressions, you can use this conditions to perform a regex match.

if [[ “$email” =~ “b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,4}b” ]]; then
echo “$email contains a valid e-mail address.”
fi

3. Arithmetic (number-based) conditions:

Condition True if Example/explanation
[ NUM1 -eq NUM2 ] NUM1 is EQual to NUM2. These conditions only accept integer numbers. Strings will be converted to integer numbers, if possible. Some random examples:

if [ $? -eq 0 ]; then # $? returns the exit status of the previous command
echo “Previous command ran succesfully.”
fi

if [ $(ps -p $pid -o ni=) -ne $(nice) ]; then
echo “Process $pid is running with a non-default nice value”
fi

if [ $num -lt 0 ]; then
echo “Negative numbers not allowed; exiting…”
exit 1
fi

[ NUM1 -ne NUM2 ] NUM1 is Not Equal to NUM2.
[ NUM1 -gt NUM2 ] NUM1 is Greater Than NUM2.
[ NUM1 -ge NUM2 ] NUM1 is Greater than orEqual to NUM2.
[ NUM1 -lt NUM2 ] NUM1 is Less Than NUM2.
[ NUM1 -le NUM2 ] NUM1 is Less than or Equal to NUM2.

4. Miscellaneous conditions:

Condition True if Example/explanation
[ -o shelloption ] shell option ‘shelloption’ is enabled. Shell options modify the behaviour of bash, except a few unmodifiable ones that indicate the shell status.

if [ ! -o checkwinsize ] # An exclamation mark inverts the outcome of the condition following it
echo “Shell option checkwinsize is disabled; enabling it so you can resize you terminal window without problems.”
shopt -s checkwinsize # This shell option is modifiable
fi

if [ -o login_shell ]; then
echo “This a a login shell.” # This shell option is not modifiable

fi

With the double-parenthesis syntax, you can use the following conditions:

5. Double-parenthesis syntax conditions:

Condition True if Example/explanation
(( NUM1 == NUM2 )) NUM1 is equal to NUM2. These conditions only accept integer numbers. Strings will be converted to integer numbers, if possible. Some random examples:

if (( $? == 0 )); then # $? returns the exit status of the previous command
echo “Previous command ran succesfully.”
fi

if (( $(ps -p $pid -o ni=) != $(nice) )); then
echo “Process $pid is running with a non-default nice value”
fi

if (( $num < 0 )); then
echo “Negative numbers not allowed; exiting…”
exit 1
fi

(( NUM1 != NUM2 )) NUM1 is not equal to NUM2.
(( NUM1 > NUM2 )) NUM1 is greater than NUM2.
(( NUM1 >= NUM2 )) NUM1 is greater than or equal to NUM2.
(( NUM1 < NUM2 )) NUM1 is less than NUM2.
(( NUM1 <= NUM2 )) NUM1 is less than or equal to NUM2.

After this dry information load, here’s a bit of explanation for those who want to know more…

Conditions in bash scripting (if statements)的更多相关文章

  1. Raising Error Conditions with MySQL SIGNAL / RESIGNAL Statements

    http://www.mysqltutorial.org/mysql-signal-resignal/ Summary: in this tutorial, you will learn how to ...

  2. 高级Bash Scripting系列笔记--01之“什么情况不适用Bash Script”

      1. 占用资源的任务,尤其那些影响速度的工作 比如排序,哈希,递归等等. 2. 大量使用数学运算 尤其是浮点运算,比如任意精度的计算或者复数计算等等,这类使用C++会好很多. 3. 跨平台的(适用 ...

  3. Bash Scripting Learn Notes

    References: [1] http://www.tldp.org/LDP/Bash-Beginners-Guide/html/ 1. Executing programs from a scri ...

  4. Linux学习书目

    Linux基础 1.<Linux与Unix Shell 编程指南> C语言基础 1.<C Primer Plus,5th Edition>[美]Stephen Prata著 2 ...

  5. linux学习书籍推荐linux学习书籍推荐

    引用地址:http://www.cnblogs.com/notepi/archive/2013/06/15/3137103.html Linux 学习书目推荐 Linux基础 1.<Linux与 ...

  6. job interview

    一 , 7series clock 二, SDRAM comtroller (DDR) 4.熟悉DDR2/3协议或Ethernet相关协议,并有实际项目经验者优先: 三,AXI bus(AMBA) 四 ...

  7. 国外大神Leo-G的 DevopsWiki

    https://raw.githubusercontent.com/Leo-G/DevopsWiki/master/README.md 总结的太好了,直接把md文件贴过来好了!慢慢学习!分享给大家,觉 ...

  8. “Clang” CFE Internals Manual---中文版---"Clang"C语言前端内部手册

    原文地址:http://clang.llvm.org/docs/InternalsManual.html 译者:史宁宁(snsn1984) "Clang"C语言前端内部手册 简介 ...

  9. Ansible@一个有效的配置管理工具--Ansible configure management--翻译(十)

    未经书面许可,.请勿转载 Custom Modules Until now we have been working solely with the tools provided to us by A ...

随机推荐

  1. poj 2318 TOYS 点与矩形的关系

    题目链接 题意 有一个矩形盒子,\(n(n\leq 5e4)\)条线段将其分成了\(n+1\)个区域(每条线段的两个端点分别在矩形的上边和下边,且线段互不相交).现向盒子中扔\(m(m\leq 5e4 ...

  2. AxureRP8 实现时间功能

    利用AxureRP8中空间的动态面板的状态改变时间设置文本的值,从而实现时间功能,如下内容. 1.新建index页面,如已有index页面忽略这步即可. 2.拖入一个文本标签,将文本标签的名称命名为: ...

  3. hdu 1565&hdu 1569(网络流--最小点权值覆盖)

    方格取数(1) Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Su ...

  4. 在github上创建自己的代码仓库

    git用了很久了,github也用很久了,但一直都是使用别人的项目, 最近想把自己写的一些代码放到自己的帐号上去 以为就是很简单的代码推送,真正做一次时候才发现,原来坑还不少呢, 就把这次的经历记录一 ...

  5. DNA的复制

    半保留复制 DNA分子复制时, DNA分子的双螺旋将解开, 互补的碱基之间的氢键断裂, 解开的两条单链作为复制的模板, 游离的脱氧核苷酸依据碱基互补配对的原则, 通过形成氢键结合到作为模板的单链上. ...

  6. python导入sklearn模块出现DLL load failed的解决办法

    笔者安装的python版本是2.7.6,最近在导入sklearn(版本:0.16.1)的模块时,经常出现DLL load failed的报错,具体截图如下: 解决办法与步骤如下: 由于sklearn的 ...

  7. InnoDB: Warning: a long semaphore wait 解决办法

    http://blog.csdn.net/wulantian/article/details/37560849

  8. js/jq仿window文件夹框选操作插件

    0.先给大家看看效果: 1.创建一个index.html文件 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...

  9. Handler处理机制

    handler缺点:如果要运送两种类型的数据(比如一个Bitmap,一个Object)就不能运送,但可以用Bunder来传输  *    使用handler的步骤:  *    1.创建一个handl ...

  10. byte 单位换算

    1G就1GB啦,平时人们说1G只是简洁来说而已. bit(位).B(字节).K(千).M(兆).G(吉咖).T(太拉) B(Byte).KB(KiloByte).MB(MegaByte).GB(Gig ...