如何检查 bash 脚本的输出是否包含 Objective-C 中的某个字符串?

How check if output of bash script contains a certain string in Objective-C?

提问人:aronsommer 提问时间:2/23/2022 最后编辑:aronsommer 更新时间:2/24/2022 访问量:78

问:

如果 shell 脚本的输出包含字符串“Caddy 2 serving static files on :2015”,我想做点什么。这就是我目前所拥有的,但沙滩球只是在旋转。这似乎是因为我的 bash 脚本中的最后一个命令启动了服务器。bash 脚本中没有出口,因此它不会结束。bash 脚本的输出是正确的,我可以看到“Caddy 2 在 :2015 上提供静态文件”。但似乎这段代码只适用于一个有尽头的 bash 脚本。

如果有人想尝试,您可以在这里下载我在 bash 脚本中使用的可执行 caddy 文件: https://caddyserver.com/download

- (IBAction)localHost:(id)sender
{
    // execute bash script to start server
    NSTask *task = [[NSTask alloc] init];
    [task setLaunchPath:@"/bin/bash"];
    [task setArguments:[NSArray arrayWithObjects:[[NSBundle mainBundle] pathForResource:@"caddy-start" ofType:@""], nil]];
    
    NSPipe *pipe = [NSPipe pipe];
    [task setStandardOutput: pipe];
    NSFileHandle *file = [pipe fileHandleForReading];
    
    [task launch];
    
    NSData *data = [file readDataToEndOfFile];
    NSString *result = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
    
    NSLog(result);
    
    NSString *string = result;
    NSString *substring = @"Caddy 2 serving static files on :2015";
    if ([string rangeOfString:substring].location != NSNotFound) {
        NSLog(@"Yes it does contain that substring");
    }
    else if ([string rangeOfString:substring].location == NSNotFound) {
        NSLog(@"No it does NOT contain that substring");
    }
}

这是我的 bash 脚本:

#!/bin/bash
DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
cd "${DIR}"

pwd

#open http://localhost:2015

# kill server if already running
kill -9 $(lsof -ti:2015)
(./caddy_darwin_amd64 stop) &
(./caddy_darwin_amd64 file-server --listen :2015 --root Content/) &
objective-c nsstring nstask

评论

0赞 R4N 2/23/2022
您是否尝试过单步执行并确定代码停滞的位置?我用 bash 脚本尝试了您的代码并删除了 loadPage 调用,它输出“是的,它确实包含该子字符串”echo Caddy 2 serving static files on :2015
0赞 aronsommer 2/23/2022
我认为问题出在和之间。我可以看到输出,但它从不记录结果。bash 脚本确实启动了一个服务器,并且它没有出口。我尝试像这样在后台运行 bash 脚本中的命令,但它没有帮助。[task launch];NSLog(result);(command) &
0赞 aronsommer 2/23/2022
我已经在上面发布了我的 bash 脚本。似乎问题是我的 bash 脚本的最后一个命令。它永远不会结束,因为它启动了一台服务器。
0赞 Larme 2/23/2022
的输出是什么?我不熟悉这些 bash 命令,但它是异步的吗?它出现了吗?做什么 ?NSLog(result);loadPage:
0赞 aronsommer 2/23/2022
“Caddy 2 serving static files on :2015”确实出现在 bash 脚本的输出中。bash 脚本中的最后一个命令确实启动了服务器,并且没有出口。NSLog 不会记录结果,因为脚本在任务启动后卡住。我认为这是因为 bash 脚本中没有出口,所以没有尽头。等待 3 秒后的东西无关紧要。

答: 暂无答案