To solve a specific problem i'm trying to make a switch for stealth mode
on macos
using bash
Here is part of the code:
STEALTH_STATUS=$(/usr/libexec/ApplicationFirewall/socketfilterfw --getstealthmode)
if [ "$STEALTH_STATUS" = "Stealth mode enabled" ]; then
/usr/libexec/ApplicationFirewall/socketfilterfw --setstealthmode off
else
/usr/libexec/ApplicationFirewall/socketfilterfw --setstealthmode on
fi
Everything seems to look ok (right?), but it doesn't work. For debug, I changed the reaction to the condition to True
and False
:
STEALTH_STATUS=$(/usr/libexec/ApplicationFirewall/socketfilterfw --getstealthmode)
if [ "$STEALTH_STATUS" = "Stealth mode enabled" ]; then
echo "True"
else
echo "False"
fi
(if we use a $STEALTH_STATUS
without "
, we get an error line 2: [: too many arguments
)
And when executing this code, it always get False
, which makes it clear that the result of executing the function to set $STEALTH_STATUS
is not equal to "Stealth mode enabled"
But if we run the command in the shell, we can make sure that the mode is enable now
$ /usr/libexec/ApplicationFirewall/socketfilterfw --getstealthmode
> Stealth mode enabled
Just another one check to make a sure
STEALTH_STATUS=$(/usr/libexec/ApplicationFirewall/socketfilterfw --getstealthmode)
STRING="Stealth mode enabled"
echo $STEALTH_STATUS
echo $STRING
if [ "$STEALTH_STATUS" = "$STRING" ]; then
echo "True"
else
echo "False"
fi
And we got...
> Stealth mode enabled
> Stealth mode enabled
> False
Can someone explain where I went wrong?
CodePudding user response:
The response from STEALTH_STATUS=$(/usr/libexec/ApplicationFirewall/socketfilterfw --getstealthmode)
contains a trailing whitespace, so your if
check is failing. You can see it by checking the length of the strings. One mechanism for trimming the whitespace is to pipe to xargs.
Here is a modified version of your script:
#!/bin/bash
current_status="$(/usr/libexec/ApplicationFirewall/socketfilterfw --getstealthmode | xargs)"
enabled="Stealth mode enabled"
echo "${current_status} length: ${#current_status}"
echo "${enabled} length: ${#enabled}"
if [ "$current_status" = "$enabled" ]; then
echo "True"
else
echo "False"
fi
Output:
$ ./script
Stealth mode enabled length: 20
Stealth mode enabled length: 20
True
Output without the pipe to xargs:
$ ./script
Stealth mode enabled length: 21
Stealth mode enabled length: 20
False
(Note, you may also want to avoid using all-caps for your variable names per bash scripting best practices)