0

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. :)

Speeed
  • 79
  • 5

1 Answers1

2

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 ()

0stone0
  • 34,288
  • 4
  • 39
  • 64
  • Oh I didn't know that you could call a function in bash like that! I'm used to standard coding conventions in other languages, thank you! – Speeed Oct 29 '21 at 15:17
  • In the shell, functions (and aliases) are intended to look to the user just like any other command. – glenn jackman Oct 29 '21 at 15:59