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
lsis not the best tool for the job. It would be better toset -- *(possibly settingnullgloband/ordotglobinbashfirst) and then look at"$#". – Kusalananda Jul 05 '21 at 14:56lssection, 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 usingzshshell – alper Jul 05 '21 at 17:29shoptis a builtin utility in thebashshell. You tagged your question with the [tag:bash] tag. – Kusalananda Jul 05 '21 at 18:22zshshell. – Kusalananda Jul 05 '21 at 18:24bashby 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 redirectinglsorgit diffresults intoless -R. I just wanted to ignore redirecting intoless -Rif the command's output is empty and do nothing – alper Jul 05 '21 at 20:01git ... | ifne less– muru Jul 06 '21 at 07:41ifnein zsh shell? @muru – alper Jul 06 '21 at 23:17moreutilspackage. You'll need to install that package. – muru Jul 07 '21 at 09:54