bash pipestatus in backticked command?

后端 未结 3 666
一整个雨季
一整个雨季 2020-12-20 22:56

in bash, if I execute a couple of commands piped together inside of backticks, how can I find out the exit status of the first command?

i.e. in this case, I am tryin

3条回答
  •  执笔经年
    2020-12-20 23:50

    Try to set pipefail option. It returns the last command of the pipeline that failed. One example:

    First I disable it:

    set +o pipefail
    

    Create a perl script (script.pl) to test the pipeline:

    #!/usr/bin/env perl
    
    use warnings;
    use strict;
    
    if ( @ARGV ) { 
        die "Line1\nLine2\nLine3\n";
    }
    else {
        print "Line1\nLine2\nLine3\n";
    }
    

    Run in command-line:

    myvar=`perl script.pl | tail -1`
    echo $? "$myvar"
    

    That yields:

    0 Line3
    

    It seems correct, let see with pipefail enabled:

    set -o pipefail
    

    And run the command:

    myvar=`perl script.pl fail 2>&1 | tail -1`
    echo $? "$myvar"
    

    That yields:

    255 Line3
    

提交回复
热议问题