jspooner
jspooner

Reputation: 11315

Bash if condition

I'd like to write a bash script that looks at security list-keychains to see if there is a keychain named appledev. If there is not a keychain I'd like to create it with this security create-keychain -p foo appledev

I was trying todo something like this but it's ridiculously incorrect.

APPLEDEVKEYCHAIN=`security list-keychains | grep appledev`
if [[$APPLEDEVKEYCHAIN -eq 1]]; then
  echo "Using keychain ${APPLEDEVKEYCHAIN}"
else
  echo "Creating Keychain appledev"
  security create-keychain -p foo appledev
fi
exit

Upvotes: 0

Views: 265

Answers (1)

grep returns a success exit code if it finds anything. The following would work:

if security list-keychains | grep -q appledev; then
  echo "Got keychain"
else
  echo "Creating keychain"
  security create-keychain -p foo appledev
fi

(-q is the "quiet" switch to grep; this prevents grep from printing anything.)

Some other things that might help with your Bash shell scripting:

  1. Backquotes are dated and error-prone. Use $(command) instead.
  2. When using command substitution ($(command) (or, heaven forbid, backquotes)), put double quotes around the substitution.
  3. The double-bracket special command needs spaces around the [[ and ]] in order to work.

Upvotes: 3

Related Questions