条件shell脚本
问题描述:
我有以下shell脚本:条件shell脚本
#!/bin/sh
output=`./process_test.sh status_pid | grep "NOT STARTED: process_1" --line-buffered`
if[[ -z ${output} ]]
then
echo "process is not running"
else
echo "process is running"
fi
其中./process_test.sh status_pid
是我查找进程是否正在运行或不.e.g效用。如果process_1
未运行,则将显示:NOT STARTED: process_1
。进一步 这个工具是完美的,没有任何问题。我怀疑问题是与if
语法
上运行该脚本,我得到以下的输出:
./test.sh: line 18: if[[ -z NOT: command not found
./test.sh: line 19: syntax error near unexpected token `then'
./test.sh: line 19: `then'
你能帮助解决这个问题?
答
必须使用空格来分隔关键字,例如if
与参数或命令(如[[
)。
#!/bin/sh
output=$(./process_test.sh status_pid | grep -e "NOT STARTED: process_1" --line-buffered)
if [[ -z ${output} ]]
then
echo "process is not running"
else
echo "process is running"
fi
答
你应该把它写像
if [[ -z ${output} ]]
then
...
所以,你已经错过了。
答
这将是一个更加简洁写这篇文章:
#!/bin/sh if ! ./process_test.sh status_pid | grep "NOT STARTED: process_1" > /dev/null; then echo "process is not running" else echo "process is running" fi
注意,--line缓冲的说法是无关紧要的,因为 管道是不会结束直到所有输入的 是读。 (嗯,这并不完全不相关 - 它会使 脚本运行速度慢得可以忽略不计。)
另请注意'[['不是标准的。根据shell language specification,其 “可能被识别为(a)在某些实施方式上保留(单词)...,导致未指定的结果”。换句话说,它就是通常所说的“bashism”(虽然它在bash以外的shell中是有效的),并且如果使用它,则不得使用#!/bin/sh
作为解释器,但应指定#!/bin/bash
。
你用问题和答案的编辑来击败我。 :)速度+1 ... – 2012-01-04 08:08:19