Home > Software engineering >  I want to take in using the user's input, then call a function using a case statement
I want to take in using the user's input, then call a function using a case statement

Time:10-30

I'm working within bash and I'm struggling to take the user's input then move them into a function. I'm using a case statement to get it to work and this is the code I'm currently working with:

read -n1 -p "Save to log? [y,n] " choice \n
case $choice in
    y|Y) echo yes ;;
    n|N) echo no ;;
    *) echo dont know ;;
esac

function saveToLog(){
    echo Saving to log
}

And i've tried what I thought would work here:

read -n1 -p "Save to log? [y,n] " choice \n
case $choice in
    y|Y) saveToLog() ;;
    n|N) echo no ;;
    *) echo dont know ;;
esac

function saveToLog(){
    echo Saving to log
}

But that doesn't work, I've done some googling and I can't find a solution using a case statement as I'd like to keep using this system.

Thank you. :)

CodePudding user response:

There's no need for the () behind saveToLog:

#!/bin/bash

read -n1 -p "Save to log? [y,n] " choice \n
case $choice in
    y|Y) saveToLog ;;
    n|N) echo "no" ;;
    *) echo "dont know" ;;
esac

function saveToLog(){
    echo "Saving to log"
}

Will call saveToLog on y|Y


Note: saveToLog must be delared as it is (using the function keyword) for this to work. Please take a look at this Stackoverflow question for more information about function and ()

  •  Tags:  
  • bash
  • Related