Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash Subshell Variable Command not Found

Tags:

bash

I'm trying to run a command and interpret the results, but whatever I do I get a "command not found" error. Here's a representative version of my code:

devicename="emulator-5554"
search=$(adb devices | grep -w "$devicename" | grep -w device)

until $search; do
     echo  "Waiting..."
     sleep 10
done

I've tried every variation that I can think of, including ...

search=$(adb devices | grep -w $devicename | grep -w device)

and

search=$(adb devices | grep -w ${devicename} | grep -w device)

..., but all return the same error.

How can I get the variable to be interpreted correctly?

like image 506
user3063045 Avatar asked Mar 20 '26 00:03

user3063045


1 Answers

The code you have runs the adb|grep|grep pipeline once only and stores the output in $search. Reading from $search doesn't re-run the pipeline.

Don't use variables to hold commands. Use functions.

search() {
    adb devices | grep -w "$devicename" | grep -qw device
}

until search; do
     echo  "Waiting..."
     sleep 10
done

Notice that I added -q to silence the final grep. You don't need to know what it found, just that it found something. Its exit code is all that matters; its output is irrelevant.

You could inline the function if you want.

until adb devices | grep -w "$devicename" | grep -qw device; do
     echo  "Waiting..."
     sleep 10
done

Or you could make $devicename a parameter, if you wish.

search() {
    adb devices | grep -w "$1" | grep -qw device
}

until search "$devicename"; do
     echo  "Waiting..."
     sleep 10
done
like image 65
John Kugelman Avatar answered Mar 21 '26 14:03

John Kugelman