Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

The title says it all. After Im prompted, I want yes and no to respectively call a function.

# Check to see if you ran this script before

echo
echo I need to know if this is your first time...
while true; do
    read -p "" yn
        case $yn in
            [Yy]* ) new;;
            [Nn]* ) exit;;
                * ) echo "Please answer yes or no.";;
            esac
done

# Define function as new
new (){
    clear; echo As you are new, I will need a few things.
} 

# Define function as root

root(){
    echo "$(tput setaf 6)Hello, world$(tput sgr0)"
}
echo

If the user inputs "y" I want the script to call the function "new". As it is now, the script will try to run a program called "new" that doesn't exist. LOL. Thanks

share|improve this question
    
Did you try calling it with brackets: new()? – Danatela May 21 '14 at 1:58
    
Yes I did. I got errors. – rombreaker May 21 '14 at 2:01
up vote 2 down vote accepted

You need to define your functions before you call them:

# Define function as new
new (){
    clear; echo As you are new, I will need a few things.
} 

# Check to see if you ran this script before
echo
echo I need to know if this is your first time...
while true; do
    read -p "" yn
        case $yn in
            [Yy]* ) new;;
            [Nn]* ) exit;;
                * ) echo "Please answer yes or no.";;
            esac
done
share|improve this answer
    
Sweet. Thanks Man/Woman – rombreaker May 21 '14 at 2:02

Assuming this is bash, each line in your script will be read from least to greatest. I.E. "Line 1, then line 2, then line 3, and so on. With this in mind, you can create many, many functions in a script and call them each one right after the other like so:

#!/bin/bash

func_1() {
echo "Doing something."
}

func_2() {
echo "Doing something again."
}

func_3() {
echo "Doing something for the last time."
}

func_1
func_2
func_3

However, in order to call each function, the call always has to be after the definition like so:

#!/bin/bash

func_1() {
echo "Doing something."
}

func_2() {
echo "Doing something again."
}

func_3() {
echo "Doing something for the last time."
}

until [ "$SOMETHING" == "SOMETHING_1" ]
do
func_1
done

until [ "$SOMETHING_2" == "SOMETHING_3" ]
do
func_2
done

until [ "$SOMETHING_4" == "SOMETHING_5" ]
do
func_3
done

This will help to better utilize functions in your more complex scripts. Hope this helped.

share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .