test命令可以用[ ]替换,前后空格必须要有
Spaces must appear after the [ and before the ]
if [ "$name" = julio ]
then
echo "Would you like to play a game?"
fi
数字比较
Operator Returns TRUE (exit status of 0) if
code | meaning |
---|---|
int 1 -eq int 2 | int 1 is equal to int 2 |
int 1 -ge int 2 | int 1 is greater than or equal to int 2 |
int 1 -gt int 2 | int 1 is greater than int 2 |
int 1 -le int 2 | int 1 is less than or equal to int 2 |
int 1 -lt int 2 | int 1 is less than int 2 |
int 1 -ne int 2 | int 1 is not equal to int 2 |
文件
Operator | Returns TRUE (exit status of 0) if |
---|---|
-d | file file is a directory |
-e | file file exists |
-f | file file is an ordinary file |
-r | file file is readable by the process |
-s | file file has nonzero length |
-w | file file is writable by the process |
-x | file file is executable |
-L | file file is a symbolic link |
逻辑或
[ -n "$mailopt" -o -r $HOME/mailfile ]
逻辑AND
[ -f "$mailfile"
-a
-r "$mailfile" ]
用括号
[ \( "$count" -ge 0 \) -a \( "$count" -lt 10 \) ]
else
user="$1"
if who | grep "^$user " > /dev/null
then
echo "$user is logged on"
else
echo "$user is not logged on"
fi
$
case
case value in
pattern 1 )
command
command
...
command;;
pattern 2 )
command
command
...
command;;
...
pattern n )
command
command
...
command;;
esac
The word value is successively compared against the values pattern 1 , pattern 2 , …, pattern n ,
until a match is found. When a match is found, the commands listed after the matching
value are executed, up to the double semicolons, which serve as a “break” statement that
shows you’ve finished specifying commands for that particular conditional. After the double
semicolons are reached, the execution of the case is terminated. If a match is not found, none
of the commands listed in the case is executed。
每个in后面,结尾必须用”;;”结尾。
正则表达式
? can be used to specify any single character; * can be used to specify zero
or more occurrences of any character; and [ … ] can be used to specify any single character
enclosed between the brackets.
case支持正则表达式
case "$hour"
in
0? | 1[01] ) echo "Good morning";;
1[2-7]
) echo "Good afternoon";;
*
) echo "Good evening";;
esac
$
使用符号|在case中标示逻辑或
The && and || Constructs
command 1 && command 2
anywhere that the shell expects to see a command, command 1 will be executed, and if it returns
an exit status of zero (success), command 2 will be executed. If command 1 returns a non-zero exit
status (fail), command 2 is not invoked but is ignored.
sort bigdata > /tmp/sortout && mv /tmp/sortout bigdata
等价
if sort bigdata > /tmp/sortout
then
mv /tmp/sortout bigdata
fi
The || construct works similarly, except that the second command gets executed only if the
exit status of the first is nonzero. So if you write
grep "$name" phonebook || echo "Couldn't find $name"
等价
if grep "$name" phonebook
then
else
echo "Couldn't find $name"
fi