1

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

2 Answers 2

0

[ (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.

0
0

In your piped statement only the exit status of the last grep is used and you do not need the test brackets. You can also eliminate the first grep.

if dscl . -list  /Users | grep -w "$username"
then
    .........
    .........
else
    .........
fi

Please test before using.

1
  • Thank you for the comment - I did that as a first gate control due to the system accounts...accounts that we don't want to delete. IE if one of our techs uses a system account name by accident I don't want that account getting deleted even by accident/ The code is intended to be reused so I wanted it to be idiot proof in case someone creates a "www" account which would be OK to delete, as opposed to _WWW which cannot be touched.
    – JasonBee
    Commented Mar 23, 2016 at 12:43

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .