[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: |
Geir Hauge |
Subject: |
Re: [Help-bash] Test exit status before printing the output without using temp file |
Date: |
Sun, 31 Jan 2016 23:03:16 +0100 |
User-agent: |
Mutt/1.5.23 (2014-03-12) |
On Sun, Jan 31, 2016 at 08:49:18AM -0600, Peng Yu 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'?
>
> printf "%s\n" "$(echo x)"
> printf "%s\n" "$(echo -n x)"
One trick is to add an extra character at the end so it doesn't end with
a newline, then remove it later when expanding the variable:
if output=$(cmd && printf ' '); then
printf 'Successful output:\n%s\n' "${output% }"
fi
--
Geir Hauge