2

I need to use the current network location inside a bash script conditional. I've tried using the scselect command, which outputs an asterisk next to the current location:

~/ scselect 
Defined sets include: (* == current set)
   70209F72-5BE9-44D1-979E-A8BA25A317B4 (Office)
 * BDF51A74-6547-4747-BD21-30C51DA26CB1 (Automatic)

This doesn't work:

#!/bin/bash
if [ `scselect | grep "*.*Automatic"` ]; then
    ...
fi

due to the * in the output of scselect that expands into the filename list in the current directory.

3 Answers 3

3

awk to the rescue.

$ scselect | awk '{if ($1=="*") print $3}'
(Automatic)

If you like you can also use sed to strip the parens.

$ scselect | awk '{if ($1=="*") print $3}' | sed 's/[()]//g'
Automatic
0

You could just escape the * with a \. Also, it looks like scselect, at least on Snow Leopard, outputs the defined sets to stderr instead of stdout, so you probably need to redirect stderr to stdout:

scselect 2>&1 | grep "\*.*Automatic"
0

This:

if [ `scselect | grep "*.*Automatic"` ]; then

Means: run the scselect command, and grep for *.*Automatic which is an invalid regular expression. The asterisk is a modifier to the previous atom ("thing") in the expression, so it can't be the first thing.

If you want to match an actual asterisk, you have to escape it with a backslash.

Spiff suggested this, but used double-quotes which will not pass the backslash on, you have to use single quotes, or a double-backslash. Confused yet? :)

So that would give:

if [ `scselect | grep '\*.*Automatic'` ]; then

Which means, run the scselect command, find the line that matches *.*Automatic and output it, then use that as the arguments to the 'test' command (also known as '[').

The test command does not take a line of output from scselect as an argument.

What you really mean to do is to not use the test command at all:

if scselect | grep '\*.*Automatic'; then

But as Spiff mentioned, for some silly reason, scselect sends its output to stderr not stdout.

So now you end up with:

if scselect 2>&1 | grep '\*.*Automatic'; then

Which works great, but still sends that line that grep is giving us to STDOUT, which we probably don't want in our output, so let's fix that:

if scselect 2>&1 | grep '\*.*Automatic' >/dev/null 2>&1; then

And... there you go.

You must log in to answer this question.

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