如何阻止Bash脚本退出时出错

时间:2017-02-08 01:37:55

标签: bash shell redis

我试图编写一个Bash脚本来检查Redis是否正在运行,如果不是,则启动它:

$this->paginate = [
        'contain' => ['ExampleTableA', 'ExampleTableB']
];
$query = $this->Users->find('all')->order(['Users.first_name'=>'ASC', 'Users.last_name'=>'ASC']);

$query_active = $this->UserParticipants->find('list', array('fields' => array('Users.id')))
    ->where(['Users.active' => 1])
    ->order(['Users.rating' => 'ASC','Users.id' => 'ASC']);

$array = $query_active->toList();
$length = $query_active->count();
$firsthalf = array_slice($array, 0, $length / 2);
$secondhalf = array_slice($array, $length / 2); 

// Extending Group      
$query->formatResults(function (\Cake\Datasource\ResultSetInterface $results) use ($firsthalf, $secondhalf) {  
    return $results->map(function ($row) use ($firsthalf, $secondhalf) {
        if($row['active'] != 1){
            $row['group'] = '-';
        }
        else{                   
            if(in_array($row['id'], $firsthalf)){
                $row['group'] = 1;
            }
            if(in_array($row['id'], $secondhalf)){
                $row['group'] = 2;
            }                   
        }
        return $row;
    });
});

$userParticipants = $this->paginate($query);

如果Redis正在运行,我会得到预期的ping=$(redis-cli ping) if [ "$ping" = PONG ] then ECHO "redis response: $ping" else response = $(redis-server /usr/local/etc/redis.conf) ECHO "$response" fi 但是,如果Redis没有运行,我会redis response:PONG而Redis无法启动。

我认为发生的事情是"无法连接" message被视为未捕获的异常,因此终止该脚本。

有没有办法捕获并完成脚本的运行?这甚至是问题吗?

1 个答案:

答案 0 :(得分:1)

以下脚本更新完全符合我的要求:

ping=$(redis-cli ping)
if [ "$ping" = PONG ]
then
    ECHO "Redis response: $ping"
else
    ECHO starting Redis
    redis-server /usr/local/etc/redis.conf
fi
ECHO "$(redis-cli ping)"

正如Janos在第二次评论中正确指出的那样,其他声明正在执行。

让我失望的是ECHO $response没有在原始剧本中打印。我猜测启动Redis的前一行是异步操作。因此,在Redis运行之前调用ECHO $response

当Redis未运行时打印出ping响应,这也被我抛弃了。脚本逻辑规定响应应仅在$ping = PONG时打印,并且应该在“Redis响应:”之前。我仍然不确定为什么会打印出“连接失败”的消息,但是还是打印...

再次感谢Janos