【问题标题】:bash script won't loop over lines in file when certain command executed执行某些命令时,bash脚本不会循环文件中的行
【发布时间】:2020-05-18 22:53:38
【问题描述】:

我的脚本从作为参数提供的文本文件中读取“.bag”文件列表。并与每个人一起做某事。 (为了清楚起见,我省略了大部分“东西”)

while IFS= read -r bag
do

    echo Extracting from $bag

    # Play the script for saving the images
    python2 extract_imgs.py --image_topics "$image_topics" --basepath "extracted_imgs/$bag_name" &
    extract_imgs_PID=$!

    # play the bag file
    rosbag play -r 10 $bag

    echo rosbag play returned: $?
    echo finished playing $bag

    # kill the subscribe node
    kill $extract_imgs_PID

done < $1

如果我注释掉 rosbag play -r 10 $bag 行,该脚本的行为与我预期的一样:它从 $1 读取每一行并运行循环的迭代,并将该行设置为 $bag。

但是使用 'rosbag play -r 10 $bag' 行,它在第一行正常工作,但随后退出循环并完成。为什么? rosbag play 的返回状态为0。我怎样才能让这个脚本运行 rosbag play 命令,然后继续循环输入文件的行?

【问题讨论】:

标签: bash loops rosbag


【解决方案1】:

问题与以下相同:

I'm reading a file line by line and running ssh or ffmpeg, only the first line gets processed!

所以解决方案是重定向标准输入:

rosbag play -r 10 $bag </dev/null

【讨论】:

    【解决方案2】:

    我将提供一个解决方案,并声明我提供的解决方案通常在这里不会很受欢迎;但无论如何...

    #!/bin/sh -x
    
    init() {
    cat >> edprint+.txt << EOF
    1p
    q
    EOF
    
    cat >> edpop+.txt << EOF
    1d
    wq
    EOF
    
    next
    }
    
    next() {
    [[ -s stack ]] && main
    end
    }
    
    main() {
    filename=$(ed -s stack < edprint+.txt)
    python2 extract_imgs.py --image_topics "$image_topics" --basepath "extracted_imgs/$bag_name" &
        extract_imgs_PID=$!
    rosbag play -r 10 ${filename}
    echo "rosbag play returned: $?"
    echo "finished playing ${filename}"
    ed -s stack < edpop+.txt
    next
    }
    
    end() {
    rm -v ./edpop+.txt
    rm -v ./edprint+.txt
    exit 0
    }
    
    init
    

    上述脚本使用包含名称的文本文件作为堆栈。 Ed 用于将每个文件名放入一个变量中,然后您可以根据该变量运行您想要的任何命令。在 main 函数结束时,再次调用 Ed 以从文件中删除第一行;两个函数(main 和 next)之间的循环迭代直到文本文件为空,此时两个 Ed 命令文件被删除,脚本终止。

    【讨论】:

    • 感谢您的回复,但解决方案是一个简单的 std_in 重定向 &lt;/dev/null 看我的回答
    猜你喜欢
    • 2017-12-04
    • 1970-01-01
    • 2012-09-30
    • 1970-01-01
    • 2017-01-04
    • 1970-01-01
    • 2014-10-04
    • 2015-02-27
    • 1970-01-01
    相关资源
    最近更新 更多