linux 如何将参数作为输入传递给另一个函数?

ulmd4ohb  于 2023-03-29  发布在  Linux
关注(0)|答案(2)|浏览(146)

所以我在Bash脚本中有两个函数,但我不太确定如何在函数中调用另一个函数并注入一个输入,以便它完成该特定函数的操作。

function DoingSomething {
    read -r input
    if [ "$input" == '1' ]; then
    #do this action

    elif ["$input" == '2' ]; then
    #do this other action
    else
    echo -e "Enter something correct!"
    fi
}

function DoingThat {
    if [ $param -gt 50 ];
    then `DoingSomething`
#Essentially I want this function to input '2' into DoingSomething when its called

    else
    echo -e "You are okay!"
    fi
}

任何帮助都很感激!:)
我尝试使用&&命令。

then `DoingSomething` && "2"
pbpqsu0x

pbpqsu0x1#

要求交互式输入是一个糟糕的设计选择。让函数读取参数来代替。

function DoingSomething {
    local input=$1
    if [ "$input" = '1' ]; then    # only one = for portability
        # do this action
    elif [ "$input" = '2' ]; then  # need space after [
        # do this other action
    else
        # don't use echo -e; print error messages to stderr
        echo "DoingSomething: Enter something correct!" >&2
    fi
}

您可能希望将其重构为case语句,并使用比小整数更多的助记符值。

function DoingSomething {
    case $1 in 
      'frobnicate')
        # do this action;; 
      'fuss')
        # do this other action;;
      *)
        echo "DoingSomething: Enter something correct!" >&2;;
    esac
}

如果你想要交互式的用户I/O,你可以把它放在调用函数中。

read -p "what shall we do?" action
DoingSomething "$action"

...但一般来说,阅读命令行参数对于可用性和可重用性来说是一个更好的设计选择。
当然,如果你执意要保留这个设计,解决方案是

echo 2 | DoingSomething

or(Bash-only“here string”语法)

DoingSomething <<<2
brccelvz

brccelvz2#

read -r reply意味着你想要a)从stdin读取或者B)提示用户输入。对于前一种方法,我想到了两种方法:

echo 2 | DoingSomething

# or

DoingSomething <<< 2

另一种方法是将2作为命令行参数传递给函数,例如:

DoingSomething 2

如果你(真的)想要支持这种类型的可变性,你需要在函数中添加一些逻辑,例如:

DoingSomething() {

    if [[ -n "$1" ]]                     # if a non-blank value has been passed on the command line then ...
    then
        reply="$1"                       # store said value
    else
        read -r -p "prompt: " reply      # else read from stdin
    fi
    echo "reply: $reply"
}

试驾:

$ echo 3 | DoingSomething                # stdin via pipe
reply: 3

$ DoingSomething <<< "3"                  # stdin via here-string
reply: 3

$ DoingSomething                         # stdin from user
prompt: 7                                # function displays "prompt: "; user enters "7"
reply: 7

$ DoingSomething 27                      # command line arg
reply: 27

相关问题