help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] Test exit status before printing the output without usin


From: Dave Rutherford
Subject: Re: [Help-bash] Test exit status before printing the output without using temp file
Date: Sun, 31 Jan 2016 17:31:08 -0500

On Sun, Jan 31, 2016 at 9:49 AM, Peng Yu <address@hidden> wrote:
> On Sun, Jan 31, 2016 at 2:03 AM, Geir Hauge <address@hidden> wrote:
> > On Sat, Jan 30, 2016 at 08:49:00PM -0600, Peng Yu wrote:
> >> Hi, Suppose I want to only print the output of a program if the exit
> >> status is 0.
> >>
> >> So far, I can only find a solution using a temp file. That is, pipe
> >> the output of the program to a temp file and then test the exist
> >> status of the program. If the exit status is 0, then I cat the content
> >> in the temp file.
> >>
> >> Does anybody know if it is possible to have a solution without a temp
file?
> >
> > You can store it in a variable:
> >
> >     if output=$(cmd); then
> >         printf 'Success! The output was:\n%s\n' "$output"
> >     fi
>
> But the trailing '\n' will be removed in `$()`. Is there a way to
> preserve the trailing '\n'?

That actually removes all the '\n''s (changing internal ones to spaces.)
In the following, the reason for the '-n' to `echo' is that mapfile
not only preserves endlines, but stores them in the variable,
so just echoing each line would get you *too many*.

set +m
shopt -s lastpipe
if cmd | mapfile; then    # did you want to redirect stderr to /dev/null?
    for w in "address@hidden"; do
        echo -n "$w"
    done
fi

Chet, there's a nit here with comments in interactive mode. To wit,
$ if true; then #yeah it's true
> echo super
> fi
super
$ [uparrow]if true; then #yeah it's true echo super; fi
> [command incomplete now that the comment is in the history]

I can see this mostly being an issue when pasting from a script
to the command line.  The command would work.. once.
That was with 4.4.0(3)-beta but the same thing happens
with 4.2.37(1)-release.

Dave


reply via email to

[Prev in Thread] Current Thread [Next in Thread]