shell中的特殊字符
- # 注释字符
- ; 行分割字符
- ;; case 终结字符
- . source 命令
- :空命令
注释
以 # 开头的行是一行注释。
#this is a comment
#号可以在本行的空白或者tab后面
#this is also a comment
注释也可以嵌入在管道中:
initial=( `cat "$startfile" | sed -e '/#/d' | tr -d '\n' |\
# Delete lines containing '#' comment character.
sed -e 's/\./\. /g' -e 's/_/_ /g'` )
# Excerpted from life.sh script
注意:有些shell命令是在一行中的,对于这种命令,shell注释并没有提供注释段的完结表示符。因此后面的内容都会被注释掉,如果想继续写命令,需要另起一行。
对于下面的情况:
#!/bin/bash
echo "The # here does not begin a comment."
echo 'The # here does not begin a comment.'
echo The \# here does not begin a comment.
echo The # here begins a comment.
echo ${PATH#*:} # Parameter substitution, not a comment.
echo $(( 2#101011 )) # Base conversion, not a comment.
- 在echo后面被引号引起来的,或者转义之后的不是注释。
- 参数替换,也不是注释
- 进制转换,也不是注释
关于case
#!/bin/bash
variable=$1
case "$variable" in
abc) echo "\$variable = abc";;
xyz) echo "\$variable = xyz";;
esac
空命令
等价于Nop, 什么都不做。运行之后,它的返回值为0,也就是shell的true。
;
echo $? #0
或者在一个死循环中:
while :
do
operation-1
operation-2
...
operation-n
done
# Same as:
# while true
# do
# ...
# done
在if 中占用空的分支,在shell中,每个分支必须要有动作。
if condition
then : # Do nothing and branch ahead
else # Or else ...
take-some-action
fi
另外可以用作命令占位符,例如如下的场景。
需要将当前用户名通过反引号赋值给username 。
: ${username=`whoami`}
# ${username=`whoami`} Gives an error without the leading :
# unless "username" is a command or builtin...
#!/bin/bash
: ${username=`whoami`}
echo $username
阻塞,防止产生新进程。
: >data
网友评论