0

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
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Dynamics
  • 7
  • 4
  • I removed a bunch of irrelevant stuff from your question and improved the indenting for readability. Please read [mre], and [ask] more generally. – wjandrea May 18 '20 at 00:28
  • Does this answer your question? [Passing parameters to a Bash function](https://stackoverflow.com/questions/6212219/passing-parameters-to-a-bash-function) – wjandrea May 18 '20 at 00:29
  • setdb $2 setdb() { if [[ -e $2 && -r $2 ]]; then...... would that be correct? – Dynamics May 18 '20 at 00:49
  • for future reference https://shellcheck.net – Jetchisel May 18 '20 at 01:16
  • @Dynamics : In this case, the $2 passed to `setdb` will be of course $1 inside `setdb`, hence `setdb() { if [[ -e $1 && -r $1 ]]; then` – user1934428 May 18 '20 at 06:58

1 Answers1

1

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
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • I cannot use select since one of the goals of the assignment is to have the user input the full argument. – Dynamics May 18 '20 at 01:40
  • 1
    OK, well as this is homework, what thoughts do you have to solve it? – glenn jackman May 18 '20 at 01:48
  • You can examine the effects of quoting a variable versus leaving it unquoted. Also investigate `set -f` – glenn jackman May 18 '20 at 01:49
  • I read over passing parameters into a bash function but im thinking arguement $2 which is test(setdb test) is not being recognized. – Dynamics May 18 '20 at 02:09
  • Set current database to be be . If the file exists and is readable, make the file the current database, respond with: Database set to If the file exists but is not readable, do not update the current database, respond with File not readable If the file does not exist, your script will create the empty named file and respond File created. Database set to If no filename is supplied, respond with: Missing Argument If too many arguments are supplied, respond with: Extra arguments ignored – Dynamics May 18 '20 at 02:10