Skip to content
Advertisement

Function Shell Script no return data

function ping {
nome=$(dialog --title "Inform o endereço que deseja PINGAR" --inputbox "IP ou URL - 
    Lembrando que será disparado 10 pings para o endereço informado." 10 45 --stdout)
status=$?
if [[ $status -eq 0 ]]; then
    ping -c 10 $nome
    rc=$?
    if [[ $rc -eq 0 ]]; then
        echo "#####################################"
        echo "## Endereço: $nome | Status: UP"  
        echo "#####################################"
    else
        echo "#####################################"
        echo "## Endereço: $nome | Status: DOWN"
        echo "#####################################"
    fi
else
    echo "Você optou por cancelar a operação."
fi }; valor=`ping`; echo "RESULTADO FOI: "$valor

When i run the script (./meuscript.sh), I have no return, only if i select cancel the dialog.

If I run the script without the function, the command is executed correctly

Advertisement

Answer

You have an endless loop. Rename the function to something else so that you don’t end up with ping calling ping calling ping calling ping

Additionally, you probably want to refactor your script substantially. Anything that looks like

command
if [[ $? == 0 ]]; then
    stuff
fi

is better written

if command; then
    stuff
fi

so you end up with something like

function renamed_ping {
    if nome=$(dialog --title "Inform o endereço que deseja PINGAR" --inputbox "IP ou URL - 
    Lembrando que será disparado 10 pings para o endereço informado." 10 45 --stdout); then
        if ping -c 10 "$nome"; then
            status="UP"
        else
            status="DOWN"
        fi
        echo "#####################################"
        echo "## Endereço: $nome | Status: $status"  
        echo "#####################################"
    else
        echo "Você optou por cancelar a operação."
    fi
}

echo "RESULTADO FOI: $(renamed_ping)"

I also took the liberty to add proper quoting, and factor out a needless variable, and remove the irregularities in the indentation.

(Having the function echo stuff and capturing it so you can echo it is still a bad smell, but then this looks like one of your first scripting exercises.)

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement