Dynamics
Dynamics

Reputation: 7

Pass second argument into Bash Function

How would I pass the 2nd argument into a bash function called setdb? I ask the user to enter a command. If the user enters setdb test, I want to pass test into the function setdb. Then I want to run a file test on it to see if test.txt exists.

#!/bin/bash

#Setdb. Checks if the file exist, read, does not exist, 
setdb () {
    if [[ -e $FILE && -r $FILE ]]; then 
        echo "Database set to" $FILE
    elif [! -f $FILE  && -w $FILE ]; then
        touch datbase.txt
        echo "File database created. Database set to database.txt"
    fi
}

while read answer; do
    if [[ $answer == "setdb" ]]; then 
        setdb
    fi
done

Upvotes: 0

Views: 155

Answers (1)

glenn jackman
glenn jackman

Reputation: 246744

You might want to use the select statement: then your users won't have to type so much:

setdb () {...}
func2 () {...}
func3 () {...}

PS3="Which function to run?"

select f in setdb func2 func3 quit; do
    case $f in
        setdb)
            read -p "Database name: " db
            setdb "$db"
            ;;
        func2) ... ;;
        func3) ... ;;
        quit) break ;;
    esac
done

Upvotes: 1

Related Questions