Issue
I wrote a for
loop to get the number of tools that haven't been installed. This is my code:
#!/bin/bash
DIALOG_INSTALLED=$(which dialog)
BREW_INSTALLED=$(which brew)
TELNET_INSTALLED=$(which telnet)
UNINSTALLED_TOOLS=0
for installed_for in $DIALOG_INSTALLED $BREW_INSTALLED $TELNET_INSTALLED; do
if [[ -z $installed_for ]]; then
let "$UNINSTALLED_TOOLS+=1"
fi
done
echo $UNINSTALLED_TOOLS
My problem is that when I go to run the code, $UNINSTALLED_TOOLS
is still equal to 0. To find the root of the issue, $UNINSTALLED_TOOLS=3
before and after the for
loop. Both of these adjustments changed the final value of $UNINSTALLED_TOOLS
to 3. Now I know that the issue lies within the for
loop. It's as if the code is skipping over the for
loop. I don't get any syntax errors so I'm very confused.
Any help is appreciated.
Solution
Assume dialog
is not found. After variable substitution, you get:
for installed_for in /usr/local/bin/brew /usr/local/bin/telnet; do
So $installed_for
never has an opportunity to be an empty string. Once you make for
loop with the empty string, your let
is incorrect, too, since after the substitution you have
let 0+=1
which makes no sense. So:
DIALOG_INSTALLED=$(which dialog)
BREW_INSTALLED=$(which brew)
TELNET_INSTALLED=$(which telnet)
INSTALLED_ARRAY=("$DIALOG_INSTALLED" "$BREW_INSTALLED" "$TELNET_INSTALLED")
UNINSTALLED_TOOLS=0
for installed_for in "${INSTALLED_ARRAY[@]}"; do
if [[ -z "$installed_for" ]]; then
let UNINSTALLED_TOOLS+=1
fi
done
echo "$UNINSTALLED_TOOLS"
Answered By - Amadan Answer Checked By - Pedro (WPSolving Volunteer)