2011-03-11 202 views
0

我有这样的shell脚本。shell脚本错误

line="[email protected]" # get the complete first line which is the complete script path 
name_of_file = ${line%.*} 
file_extension = ${line##*.} 
if [ $file_extension == "php"] 
then 
ps aux | grep -v grep | grep -q "$line" || (nohup php -f "$line" > /var/log/iphorex/$name_of_file.log &) 
fi 
if [ $file_extension == "java"] 
then 
ps aux | grep -v grep | grep -q "$line" || (nohup java -f "$name_of_file" > /var/log/iphorex/$name_of_file.log &) 
fi 

这里线变量具有像/var/www/dir/myphp.php/var/www/dir/myjava.java值。

shell脚本的目的是检查这些进程是否已经在运行,如果没有,我尝试运行它们。我得到以下错误。

name_of_file: command not found 
file_extension: command not found 
[: missing `]' 
[: missing `]' 

任何想法?

+0

您需要的紧密报价'间空隙的支架问题“'和括号''''如下所示...''php”]' – 2011-03-11 13:57:34

+0

什么shell?脚本是否以'#!'开头? – nmichaels 2011-03-11 13:58:12

+0

然后我得到'name_of_file:找不到命令 FILE_EXTENSION:找不到命令 [:==:一元运算符预期 [:==:一元运算符expected' – ayush 2011-03-11 13:59:05

回答

3

首先,外壳处理器对待行:

name_of_file = ${line%.*} 

作为执行者命令和灰:

name_of_file 

与参数:

= ${line%.*} 

你需要把它写成:

name_of_file=${line%.*} 

这使得它成为一个变量=值。您还需要为file_extension =行重复此操作。

其次,如果:

if [ $file_extension == "php"] 

具有完全相同的分析问题,你必须的空间尾随前],否则解析器认为你检查是否$ FILE_EXTENSION等于字符串:“PHP]”

if [ $file_extension == "php" ] 
1

先删除空间,也许这将帮助...

name_of_file=${line%.*} 
file_extension=${line##*.} 

编辑
试试这个:

if [ $file_extension="php" ] 
.. 
if [ $file_extension="java" ] 
+0

no help'name_of_file:command not found infinity.sh:line 8:file_extension:command not found infinity.sh:line 9:[:==:unary operator expected infinity.sh:line 13:[: ==:一元运算符预期 '我得到了这个错误 – ayush 2011-03-11 14:01:53

1

other answers是正确的,在你的脚本问题出在流浪的空间在您的变量赋值和[ .. ]语句。

(题外话仅供参考。)

我把重构你的脚本(未经测试的自由!)只是为了突出一些替代方案,即:

  • 使用case

使用pgrep代替ps aux | grep .....

  • -

    #!/bin/bash 
    line="[email protected]" # get the complete first line which is the complete script path 
    name_of_file=${line%.*} 
    
    pgrep "$line" > /dev/null && exit # exit if process running 
    
    case "${line##*.}" in # check file extension 
        php) 
         nohup php -f "$line" > /var/log/iphorex/$name_of_file.log & 
         ;; 
        java) 
         nohup java -f "$name_of_file" > /var/log/iphorex/$name_of_file.log & 
         ;; 
    esac 
    
  • +0

    @Chin:感谢额外的东西..看起来更干净这种方式:) – ayush 2011-03-11 21:39:26

    +0

    不客气。 – 2011-03-11 22:33:54