Bash脚本意外结束文件

时间:2014-07-02 09:17:23

标签: linux bash sleep

我有以下代码:

   #!/bin/bash -x

   # Arguments:

   #    $1 - command to run

   # $2 - time limit (in milliseconds)

   # $3 - memory limit (in kilobytes)

   # NOTE TO SELF: $! is the pid of last process

   # NOTE TO SELF: Appending & creates new process

   dir=$(mktemp -d)

   ulimit -m $3

   { $1 ; "$?" > "$dir/retc" } &

   pid=$!

   ./sleep.pl $2

   if [ ps -p $pid > /dev/null ]

   then

     kill -9 $pid

     echo "0Time Limit Exceeded"

   else

     echo "NAH"

     ret=$(cat "$dir/retc")

     if [ $ret = 9 ]

     then

       echo "0Memory Limit Exceeded"

     else

       if [ $ret = 0 ]

       then

         echo "1" # If it only returns one then it must be passed through final phase of verifying if result is correct

       else

         echo "0Received signal $ret"

       fi

     fi

   fi

   rm -r $dir

   exit 0

但是,它会返回错误"文件的意外结束",而不执行if / else块中的任何内容。

2 个答案:

答案 0 :(得分:1)

你错过了分号,重定向也是错误的:

{ $1 ; "$?"; } >"$dir/retc" &

来自bash man:list必须以换行符或分号结尾

此外:

if [ ps -p $pid > /dev/null ]

应该是:

if [[ $(ps -p $pid >/dev/null) -eq 0 ]]

答案 1 :(得分:0)

我建议使用()而不是{}来明确表明你想召唤一个子shell。另外,我认为您错过echo来显示$?的价值。

( "$1"; echo "$?" > "$dir/etc"; ) &

使用(),与{}不同,最后不需要添加分号,但这仍然是一种很好的做法。