gpt4 book ai didi

用于提示和返回输入的 shell 函数

转载 作者:行者123 更新时间:2023-12-04 18:53:54 26 4
gpt4 key购买 nike

我正在尝试编写一个辅助函数以在 bash 脚本中使用,以获取变量提示字符串并返回用户输入的值。我有什么就坐等用户输入值而不先显示提示,这很令人费解。它还将 echo 存储在返回值 ($foo) 中,并且不使用 pid 变量保留读入的值。

!#/bin/bash
pid=0
promptValue() {
msg="$1"
echo -e "$msg"
read val
pid=$val
}

foo=$(promptValue "type something")

编辑:
对于将来可能希望将其用于自己用途的任何人,这是完整的(功能性)脚本,旨在发送电子邮件(在这种情况下发送到我的手机)以在长时间运行的过程完成时通知我.我确信必须有更好的方法来做到这一点,但是嗯。 :-)(我这样写它们是为了在其他地方的 bash 函数库中使用。)
#!/bin/bash

promptValue() {
read -p "$1"": " val
echo $val
}

alertme() {
if [ -z "$email" ]; then
email=$(promptValue "Enter email")
fi

if [ -z "$email" ]; then
echo "ERROR: No email set!"
exit 1
fi

if [ -z "$pid" ]; then
pid=$(promptValue "Enter pid")
fi

if [ -z "$pid" ]; then
echo "ERROR: No pid set!"
exit 1
fi

ps -ef | grep $pid | grep -v grep > /dev/null 2>&1
while [ $? eq 0 ]; do
sleep 10
ps -ef | grep $pid | grep -v grep > /dev/null 2>&1
done

echo "Process Complete" | mailx -s "Process Complete" $email
}

alertme

再次感谢大家!

最佳答案

函数的退出值与函数内执行的最后一个命令的退出值或由 return n 提供的值相同。声明 where n范围为 0-255。如果你想让函数返回一个字符串或数字值,你可以使用 echo .如果您想在变量中捕获函数的输出,并且仍然能够在没有捕获的情况下将输出发送给用户,请使用 stderr这是什么read -p做。

$ demo() {
local num
echo "capture this"
echo "Message to user" >&2
read -p $1 num
echo $(( num * 2 ))
return 42
}
$ result=$(demo "Enter a number: ")
Message to user
Enter a number: 12
$ echo $?
42
$ echo "$result"
capture this
24
$ echo "$num"
[null][newline]

关于用于提示和返回输入的 shell 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1989439/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com