一:问题的提出
代码:
[oracle@localhost SHELL]$ lspids() {
>
> USAGE="Usage: lspids [-h] process"
> HEADER=false
> PSCMD="/bin/ps -ef"
>
> case "$1" in
> -h) HEADER=true ; shift ;;
> esac
>
> if [ -z "$1" ] ; then
> echo $USAGE ;
> return 1;
> fi
> if [ "$HEADER" = "true"] ;then
> $PSCMD 2> /dev/null | head -n 1;
> fi
> }
[oracle@localhost SHELL]$ lspids
Usage: lspids [-h] process
[oracle@localhost SHELL]$ lspids -h
Usage: lspids [-h] process
[oracle@localhost SHELL]$ lspids -h ssh
bash: [: missing `]'
如上所示,定义了一个函数 lspids() {}
运行 lspids -h ssh
后出现 bash: [: missing `]' 这个错误 ,而前面 测试运行的 2次都没有问题
二:问题的解决
正如上面所说,前两次运行都没有问题,那么细细分析代码,发现,程序执行到这里:
if [ "$HEADER" = "true"] ;then
出现了问题 ,这是因为 在 [ ] 内 要有空格 ,也就是说 "$HEADER" 前 和 "true" 后要有空格才行。
所以必须改为
if [ "$HEADER" = "true" ] ;then
这样就解决了 bash: [: missing `]'
三:解决后的代码:
[oracle@localhost SHELL]$ cat 4.sh
#! /bin/sh
lspids() {
USAGE="Usage: lspids [-h] process"
HEADER=false
PSCMD="/bin/ps -ef"
case "$1" in
-h) HEADER=true ; shift ;;
esac
if [ -z "$1" ] ; then
echo $USAGE ;
return 1;
fi
if [ "$HEADER" = "true" ] ;then
$PSCMD 2>/dev/null | head -n 1;
fi
$PSCMD 2> /dev/null | grep "$1" | grep -v grep
}
lspids $@
四:运行结果
可以运行这个脚本,也可以直接定义这个函数,不必保存为一个脚本,直接在终端运行之.
1.在终端运行结果如下:
[oracle@localhost SHELL]$ lspids() {
>
> USAGE="Usage: lspids [-h] process"
> HEADER=false
> PSCMD="/bin/ps -ef"
>
> case "$1" in
> -h) HEADER=true ; shift ;;
> esac
>
> if [ -z "$1" ] ; then
> echo $USAGE ;
> return 1;
> fi
> if [ "$HEADER" = "true" ] ;then
> $PSCMD 2>/dev/null | head -n 1;
> fi
>
> $PSCMD 2> /dev/null | grep "$1" | grep -v grep
> }
[oracle@localhost SHELL]$ lspids -h ssh
UID PID PPID C STIME TTY TIME CMD
root 2523 1 0 14:04 ? 00:00:00 /usr/sbin/sshd
oracle 2904 2869 0 14:05 ? 00:00:00 /usr/bin/ssh-agent /bin/sh -c exec -l /bin/bash -c "/usr/bin/dbus-launch --exit-with-session /etc/X11/xinit/Xclients"
最后撤销函数的定义 运行下面这个命令:
unset lspids
2.定义成脚本 4.sh ,结果如下:
[oracle@localhost SHELL]$ cat 4.sh
#! /bin/sh
lspids() {
USAGE="Usage: lspids [-h] process"
HEADER=false
PSCMD="/bin/ps -ef"
case "$1" in
-h) HEADER=true ; shift ;;
esac
if [ -z "$1" ] ; then
echo $USAGE ;
return 1;
fi
if [ "$HEADER" = "true" ] ;then
$PSCMD 2>/dev/null | head -n 1;
fi
$PSCMD 2> /dev/null | grep "$1" | grep -v grep
}
lspids $@
# 注意,最后一行必须加 $@ 因为 ,脚本中的$1 指 运行函数 后面的第一个参数 ,也就是函数名后第一个参数
运行 4.sh ,结果如下:
[oracle@localhost SHELL]$ ./4.sh -h ssh
UID PID PPID C STIME TTY TIME CMD
root 2523 1 0 14:04 ? 00:00:00 /usr/sbin/sshd
oracle 2904 2869 0 14:05 ? 00:00:00 /usr/bin/ssh-agent /bin/sh -c exec -l /bin/bash -c "/usr/bin/dbus-launch --exit-with-session /etc/X11/xinit/Xclients"
oracle 5368 3093 0 16:47 pts/1 00:00:00 /bin/sh ./4.sh -h ssh
[oracle@localhost SHELL]$
声明:本文档可以随意更改,但必须署名原作者
作者:凤凰舞者 qq:578989855