I am using solutions from Test if a command outputs an empty string. In addition to those solutions, I want to print command's output if its not empty.
I was wondering would it be possible to print command's output if its not empty by calling the command only one time.
I can do it by re-calling the same command inside the if condition
, but now second call may consume additional CPU usage, since we already obtained its result.
Possible approach could be, where the same command is called two times:
if [[ $(ls -A) ]]; then
ls -A
else
echo "no files found"
fi
output=$(git diff --ignore-blank-lines --color-words HEAD | tr -d ' \n\r\t ' | wc -c)
if [ "$output" -gt 0 ]; then
git diff --ignore-blank-lines --color-words HEAD
else
echo "diff is empty"
fi
ls
is not the best tool for the job. It would be better toset -- *
(possibly settingnullglob
and/ordotglob
inbash
first) and then look at"$#"
. – Kusalananda Jul 05 '21 at 14:56ls
section, since it leads another question as https://unix.stackexchange.com/questions/657078/how-to-redirect-ls-output-into-less-r-if-the-output-size-is-large// For @Stephen Kitt's answer than should we first set
– alper Jul 05 '21 at 15:03set -- *
?shopt -s nullglob dotglob; set -- *; [ "$#" -eq 0 ] && echo 'no files'
– Kusalananda Jul 05 '21 at 15:44shopt
? // E: Unable to locate packageshopt
// please note that I am usingzsh
shell – alper Jul 05 '21 at 17:29shopt
is a builtin utility in thebash
shell. You tagged your question with the [tag:bash] tag. – Kusalananda Jul 05 '21 at 18:22zsh
shell. – Kusalananda Jul 05 '21 at 18:24bash
by mistake by taking tags from the linked related question, and when I realize my mistake it was too late to change it. I am sorry for this. // In general I was redirectingls
orgit diff
results intoless -R
. I just wanted to ignore redirecting intoless -R
if the command's output is empty and do nothing – alper Jul 05 '21 at 20:01git ... | ifne less
– muru Jul 06 '21 at 07:41ifne
in zsh shell? @muru – alper Jul 06 '21 at 23:17moreutils
package. You'll need to install that package. – muru Jul 07 '21 at 09:54