I'm not actually having a problem with something but I was playing around with being able to find a substring from the output of a variable. I can't get this to give me the expected result.
#!/bin/zsh
proc=$(system_profiler SPHardwareDataType | grep "Chip:" | /usr/bin/awk '{print $2,$3,$4}')
echo $proc
if [ "$proc" = *"M2"* ]; then
echo "M2 processor installed"
else
echo "unknown"
fi
The correct result should be "M2 processor installed". I get "unknown". I looked up how to do this and found this site:
https://linuxize.com/post/how-to-check-if-string-contains-substring-in-bash/
After reading that site I changed my conditional statement to match the syntax in the article.
#!/bin/zsh
proc=$(system_profiler SPHardwareDataType | grep "Chip:" | /usr/bin/awk '{print $2,$3,$4}')
echo "$proc"
if [[ "$proc" = *"M2"* ]]; then
echo "M2 Processor installed"
else
echo "unknown"
fi
This works. The only change I made was to use "[[ ]]" instead of "[ ]". I have written a lot of conditional statements using "[ ]" and they all work. I have also used "[[ ]]" and they work too. Why did this not work when I used "[ ]"? Knowing this will save me a lot of annoyance in the future. When I can't get a script to work, it's most often the case that I am using the wrong syntax. I'm not new to scripting but I am always happy to get tips and advice.