jeudi 23 avril 2015

how can I pass the output of a command to a function in bash

I'm facing an issue when trying to create a function, I have a code to detect a bluetooth dongle connected to a usb, which is the first part of the code, and it works fine, if the usb is indeed plugged in, then it checks its stats (UP or DOWN) and storages it in the bt_stat variable which is printer after all, so far everything works fine

#!/bin/bash
clear    
echo "Looking for bluetooth USB"
bt_id=`lsusb|grep ASUS|cut -c24-32`
bt_stat="0"
    if [[ -z "$bt_id" ]]; then
        echo "not found"
        exit 1 
    else
        bt_stat=`hciconfig|head -3|tail -1|grep "UP\|DOWN"`
        echo "USB BT found"
    fi
echo $bt_stat

OUTPUT:

USB BT found

UP RUNNING

the problem starts when I try to pass that variable to a function

function disp
{
    eval st1="$1"
    echo "Status: ${st1}"
}

The function it self works as well, I have pass a fixed variable and the output, as expected is "Status: TEST"

var="TEST"
disp "\${var}"

but the moment I place the function at the beginning of the code, even if I don't use it, then the assignation of the command to the variable bt_stat is not even made, what can be causing this? do I have to take something in consideration when making a function in a program that is assigning the output of a command to a variable?

below is how the code looks with the function, I'm sorry for the long question, but I wanted it to be clear

#!/bin/bash
function disp
{
    eval st1="$1"
    echo "Status: ${st1}"
}
clear    
echo "Looking for bluetooth USB"
bt_id=`lsusb|grep ASUS|cut -c24-32`
bt_stat="0"
    if [[ -z "$bt_id" ]]; then
        echo "not found"
        exit 1 
    else
        bt_stat=`hciconfig|head -3|tail -1|grep "UP\|DOWN"`
        echo "USB BT found"
    fi
echo $bt_stat

OUTPUT:

USB BT found

an additional line shows if I call with disp "\${bt_stat}" the function, but the assignation is still not taking place

Status:

Aucun commentaire:

Enregistrer un commentaire