How can this code construct be optimized to avoid duplicate code (git diff --ignore-space-at-eol -U0
)?
while [ ! -z "$(git diff --ignore-space-at-eol -U0)" ]; do
diff_text=$(git diff --ignore-space-at-eol -U0);
echo $diff_text
done
In PHP it could be done like this:
while (! $diff_text = "git diff --ignore-space-at-eol -U0") {
echo $diff_text;
}
We need code so that the diff_text
variable is subtracted 1 time.
CodePudding user response:
You can insert multiple instructions inside the while condition block:
while
diff_text=$(git diff --ignore-space-at-eol -U0)
[ -n "$diff_text" ]
do
echo "$diff_text"
done
CodePudding user response:
Use an infinite loop with a break condition to add commands before the comparison that breaks the loop:
while true; do
i=$(date)
echo $i
[[ "$i" =~ "9 " ]] && break
sleep 1
done
CodePudding user response:
One option is to use a function that sets the diff_text
variable, and returns non-zero if it is empty:
function set_diff_text
{
diff_text=$(git diff --ignore-space-at-eol -U0)
[[ -n $diff_text ]] && return 0 || return 1
}
while set_diff_text; do
printf '%s\n' "$diff_text"
done
Another way to use a function to do it is:
function get_diff_text
{
local difftxt
difftxt=$(git diff --ignore-space-at-eol -U0)
printf '%s\n' "$difftxt"
[[ -n $difftxt ]] && return 0 || return 1
}
while diff_text=$(get_diff_text); do
printf '%s\n' "$diff_text"
done
- See the accepted, and excellent, answer to Why is printf better than echo? for an explanation of why I used
printf
instead ofecho
to print thegit diff
output.