Hi!
I am new to OSX Shell Script and am trying to work my way into it. I don't get the expected outcome with the following snippet of my script code and I have no idea, why. I read most of the Apple Shell Script Pimer and googled a lot about it, but to no avail.
I want to check the current username against some given usernames and set the value of a variable depending on the outcome. I used awk inside the shell script to get this done, but for some reason the for loop inside the awk part seems to change the value of the current username with every loop.
This is the code:
#!/bin/zsh
awk -v u=$USER 'BEGIN {
print "Username outside loop is " u;
count[0] = "Anton";
count[1] = "Bert";
count[2] = "Carl";
for ( c_num in count ) {
print "Username inside loop is " u;
print "Compare to "count[c_num];
if (u = count[c_num]) {
test_var = "X";
} else {
test_var = "Y";
}
print test_var;
}
}'
And this is what I get after I run it in terminal:
Username outside loop is Zac
Username inside loop is Zac
Compare to Carl
X
Username inside loop is Carl
Compare to Anton
X
Username inside loop is Anton
Compare to Bert
X
I don't see why 'u' is changed every loop.
I'm thankful for every help / advice!
Markus
-
—
OOPer
-
—
mmhld
Add a CommentAwk is an open sourced language available on various platforms. Although awk may be included in most versions of macOS, it is provided as is, no support. You should better find a better place to learn awk. (And in fact, there are so many sites about awk.) By the way, I think
=(a single equal sign) is an assignment operator in awk, not a comparison operator.Hi OOPer,
thanks for your reply. You are right in both your answers: I read a lot about awk on the web and my mistake was putting = where ~ would have been right.