Chuck Claunch
Chuck Claunch

Reputation: 1654

Bash script echos but won't execute

I'm creating a simple bash script to remove all Bluetooth devices from my system. What it does is use bt-device -l to list the bluetooth devices, then grabs the MAC address in between the parens, then calls bt-device -r <MACAddress> to remove the device. I'm not that great at bash scripts but when I replace the bt-device call with echo, I get the correct output. When I put the command back in it says the device wasn't found. If I manually make the call it works (outputs "Done").

Sample output of the bt-device -l command:

Added Devices:
Samico BP (12:34:56:78:9a:bc)
SensorTag 2.0 (12:34:56:78:9a:bd)

And the script I'm using:

#!/usr/bin/env bash

bt-device -l | sed 1d |
while read x; do
    bt-device -r $x | cut -d "(" -f2 | cut -d ")" -f1
done

When I run it, it runs the bt-device -r command but the output is Error: Device not found as if I'd typed the MAC address wrong. If I replace the bt-device call in the script with echo, I get the list of MAC addresses as expected.

Updated script working

#!/usr/bin/env bash

bt-device -l | sed 1d |
while read x; do
    bt-device -r $(echo $x | cut -d "(" -f2 | cut -d ")" -f1)
done

Upvotes: 0

Views: 58

Answers (2)

ruakh
ruakh

Reputation: 183241

The problem is that you're running cut -d "(" -f2 | cut -d ")" -f1 on the output of bt-device -r, instead of on its argument.

Instead, you should write something like this:

bt-device -l | sed 1d | cut -d "(" -f2 | cut -d ")" -f1 |
while read x; do
     bt-device -r $x
done

Upvotes: 2

unconditional
unconditional

Reputation: 7656

You'd want to process $x prior to using it:

bt-device -l | sed 1d |
while read x; do
    dev=$( echo "$x" | cut -d "(" -f2 | cut -d ")" -f1 )
    bt-device -r "$dev"
done

Upvotes: 2

Related Questions