Reputation: 1116
I am currently working on a Mac OS X software update check script/plugin for Nagios, so that I can monitor my Mac Mini and Mac Pro machines, whether they have any updates available or not.
I created a variable called swUpdateCheck
and assigned the check command to it, including some grep
and awk
, so that I can work with the output at the end. Since I don't always want to call the os update command, I just exported the output to a text file update.txt
and am currently using the text file for building the final script.
This is my variable:
swUpdateCheck=`cat update.txt | grep -B1 recommended | grep -v recommended | awk '{gsub(/^[[:cntrl:][:space:]]+|^\-+|\*\s/,"");}NF>0 1' | wc -l`
Content of the Text file:
* Security Update 2018-004-10.12.6
--
* Safari11.1.2Sierra-11.1.2
--
* iTunesX-12.8
Now my issue is, that whenever I call the variable it scans through the file and should give me a number of lines at the end when I echo it. It does give me a number when using a simple echo but as soon as I combine the variable with a string, it adds spaces in front of the number and I don't understand why.
Normal echo of swUpdateCheck
:
$ echo $swUpdateCheck
3
Echo swUpdateCheck
in a string:
$ echo "There are $swUpdateCheck Updates available."
There are 3 Updates available.
What am I missing or doing wrong?
Upvotes: 0
Views: 2030
Reputation: 141493
swUpdateCheck
has spaces in it, not just 3
. As you are not escaping the variable in echo $swUpdateCheck
spaces get reinterpreted and 3 get's printed out. If you enclose the variable in "
, as in echo ".... $swUpdateCheck ..."
spaces will not be ignored. Observe the output with set -x
:
$ set -x
$ echo
+ echo
$ swUpdateCheck=" 3" # assigment with spaces in it
+ swUpdateCheck=' 3'
$ echo 3 # leading spaces get ignored
+ echo 3
3
$ echo $swUpdateCheck # just printing '3', this is the same as above line
+ echo 3
3
$ echo "$swUpdateCheck" # with "
+ echo ' 3'
3
$ swUpdateCheck=${swUpdateCheck// /} # remove spaces using bash or use sed 's/ //g' or tr -d ' ' or other
+ swUpdateCheck=3
$ echo "$swUpdateCheck" # now swUpdateCheck is without spaces, it will work
+ echo 3
3
$ echo "There are $swUpdateCheck Updates available."
+ echo 'There are 3 Updates available.'
There are 3 Updates available.
Upvotes: 2