簡體   English   中英

將第二個參數傳遞給 Bash Function

[英]Pass second argument into Bash Function

如何將第二個參數傳遞給名為 setdb 的 bash setdb 我要求用戶輸入命令。 如果用戶輸入setdb test ,我想通過測試進入 function setdb 然后我想對其運行文件測試以查看 test.txt 是否存在。

#!/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

您可能想要使用select語句:那么您的用戶就不必輸入這么多:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM