help-bash
[Top][All Lists]
Advanced

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

Re: [Help-bash] Test if there is any output from a program, if yes, prin


From: Greg Wooledge
Subject: Re: [Help-bash] Test if there is any output from a program, if yes, print the user specified string and the output from the program? (without using a tempfile)
Date: Mon, 3 Feb 2014 08:36:46 -0500
User-agent: Mutt/1.4.2.3i

On Sun, Feb 02, 2014 at 11:57:40AM -0600, Peng Yu wrote:
> ./prog > temp.txt
> if [ -s temp.txt ]
> then
>   echo "user specified string"
>   cat temp.txt
> fi
> 
> I want to avoid the use of tempfile.

In the most general case, you can't.  You need the temp file.

In a restricted subset of the problem, you can use command substitution
to capture the output, thereby avoiding the temp file:

result=$(./prog; printf x)
result=${result%x}
if [[ $result ]]; then
  echo "mystring $result"
fi

Adding and removing the 'x' works around the command substitution feature
of removing ALL trailing newlines (instead of just one).

But this will fail if the output can contain NUL bytes.  Bash cannot store
NUL bytes in variables (or pass strings containing NUL bytes to echo),
because it uses C-style strings, where a NUL byte indicates the end of
the string.  So for those cases, the output must be kept in a file.



reply via email to

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