1

It's possible to have an if-else inside a function?

Here I have the menu.

Please see codes below.

#!/bin/bash

#Main Menu

function p_enter
{
    echo ""
    echo -n "Press Enter to continue"
    read
    clear
}

function df1
{
read var
if [ $var = "1" ]
 then
 echo "nice"
 else
 echo "not bad"
 fi
   }



    select=
    until [ "$select" = "0" ]; do
        echo ""
        echo "MAIN MENU"
        echo "1 - XML DATA REPORT"
        echo "2 - SOON "
        echo ""
        echo "0 - exit"
        echo ""
        echo -n "Enter sleection: "
        read select
        echo ""

    case $select in
            1 ) df1 ; press_enter ;;
            2 ) free ; press_enter ;;
            3 ) exit ;;
            * ) echo "nvalid entry"; press_enter
     esac
     done

Any tips or suggestions?

рüффп
  • 1,677
  • 4
  • 27
  • 35
Edmhar
  • 395
  • 2
  • 6
  • 16

1 Answers1

4

Yes, a shell function can use if/else statements.

#!/bin/bash

function comment_on_val {
    local the_reply="$1"
    local the_word="$2"

    if (( the_reply == 1 )); then
        echo "The value is one ($the_word)"
    else
        echo "The value isn't one ($the_word)"
    fi
}

echo "Menu:"
select word in "Yes" "No" "Exit"; do
    case "$REPLY" in
        3) break    ;;
        *) comment_on_val "$REPLY" "$word"   ;;
    esac
done

The only reason I use local in the function is to give the two variables local scope. If I didn't, they would exist in the main body of the script after calling comment_on_val, which in this case is not intended.

Kusalananda
  • 320,670
  • 36
  • 633
  • 936
  • so local is required on the function side? – Edmhar Jul 22 '16 at 13:46
  • @JJ-SAMA No, it's just a declaration to make them have scope within the function body. It's not required. – Kusalananda Jul 22 '16 at 13:55
  • @JJ-SAMA I added a note about this to my answer. – Kusalananda Jul 22 '16 at 14:22
  • Why did you put quotes around `$1` and `$2`? – felwithe Feb 08 '19 at 23:44
  • @felwithe Quotes are not usually needed in simple assignments like `a=$1`, and in `bash` it's not strictly needed with `export a=$1` and `declare a=$1`, but other shells need the quotes for `export a="$1"`. If in any form of doubt, always double quote all expansions. See e.g. [When is double-quoting necessary?](//unix.stackexchange.com/q/68694) – Kusalananda Feb 08 '19 at 23:50