MacOS – Problem with scripted account deletion syntax

bashcommand linemacosscript

I'm working on an account cleanup script module that can handle the hidden and unhidden accounts we're creating in bulk on new MacOS systems.

We've kept the logic simple to start.

However I keep getting an error: line 4: [: missing `]'

I have the space…what am I missing? I tried syntax checks and it passes muster.

#!/bin/bash
USERNAME=administrator

if [ dscl . -list /Users | grep -v '^_' | grep $USERNAME ];
    then
    echo "Deleting user account $USERNAME"
    dscl . -delete "/Users/$USERNAME"
else
    echo "The admin account $USERNAME does not exist here"
fi

if [ -d "/$USERPATH/$USERNAME" ];
    then
    echo "Deleting leftover user account folder $USERPATH/$USERNAME"
    rm -rf $USERPATH/$USERNAME
fi

if [ -d "/Users/$USERNAME" ];
    then
    echo "Deleting leftover user account folder /Users/$USERNAME"
    rm -rf /Users/$USERNAME]
fi

Best Answer

[ (and [[) expect an expression, not a command; so you can't directly run commands inside a test.

When you put a pipe in your condition it terminates the evaluation started with [ which makes ] to be treated as an argument to the last grep.

Try putting your condition inside $() like so:

if [ $(dscl . -list /Users | grep -v '^_' | grep $USERNAME) ];

That way the expression (including all the pipes) is going to be executed first and return its exit code to be used in your evaluation.