bashterminalmacos-ventura

(macOS Bash) 2 seemingly identical strings are not equal, only showing differences with "set -x"


1st Question on stackoverflow, please tell me if I did something wrong.

I want to collect members of the admingroup and compare them to the local users (some accounts excluded via grep -v). Comparing them kinda does not work as its always showing 2 identical strings as not equal.

I'm new to scipting and and heavily rely on googling to get anything done. I tried basically everything I found on stackoverflow via google to no avail and reviewed the similar questions, so while this seems to be a recurring topic I don't think this is a duplicate?

So heres the script:

#!/bin/bash

localuser=$(ls /Users/ | grep -v "Shared\|admin\|.localized\|_appstore\|root")
localadmin=$(dseditgroup -o read admin | grep $localuser)

if [[ "$localadmin" == "$localuser" ]]; then 
echo "true"
else
echo "false"
fi

If I echo both variables using od -c I get the following output:

0000000    m   f   r   a   n   k  \n                                    
0000007
0000000    m   f   r   a   n   k  \n                                    
0000007

Using set -x (leaving out the -if/else) I get the following:

++ ls /Users/
++ grep -v 'Shared\|admin\|.localized\|_appstore\|root'
+ localuser=mfrank
++ dseditgroup -o read admin
++ grep mfrank
+ localadmin='          mfrank'
+ echo mfrank
mfrank
+ echo mfrank
mfrank

Here I can clearly see that $localadmin has two ' and blank spaces. Where do these come from and how can I get rid of them? Why are these not showing with od -c?

Thank you very much for helping.

EDIT:

Correctly using OD shows the following:

localadmin
0000000    004411  063155  060562  065556 0000010                                
localuser
0000000    063155  060562  065556  0000006                                  

Solution

  • Your immediate problem is because $localadmin is subject to word-splitting and glob expansion, so when you ran echo $localadmin | od the whitespace was removed. Always use "$localadmin" with the quotes to prevent your data from being munged.

    When you intentionally want to remove whitespace from a variable, you can do that with ${localadmin//[[:space:]]/}.


    For your real problem, finding the name of non-root local admin users on MacOS:

    dscacheutil -q group -a name admin |
      awk '$1 == "users:" {
        for (i=2; i<=NF; i++) {
          if ($i != "root") {
            print $i
          }
        }
      }'
    

    Thank you to Ed Morton for helping with the awk. :)