gpt4 book ai didi

bash - 想要通过将命令的输出重定向到变量来检查命令是否成功

转载 作者:行者123 更新时间:2023-11-29 08:44:03 25 4
gpt4 key购买 nike

我目前正在编写一个 bash 脚本,它使用 GoogleCL 将视频文件加载到 YouTube。 .

因为我在循环上传东西(因为可以有多个视频文件),所以我想在上传下一个文件之前检查每个文件是否已成功上传。

命令 google youtube post --access unlisted --category Tech $f(其中 $f 代表文件)输出一个字符串,告诉我上传是否成功。

但我不知道如何将“返回字符串”重定向到一个变量中以检查是否成功。

这就是我所拥有的:

for f in ./*.ogv ./*.mov ./*.mp4
do
if [[ '*' != ${f:2:1} ]]
then
echo "Uploading video file $f"

# How to put the return value of the following command into a variable?
google youtube post --access unlisted --category Tech $f > /dev/null

# Now I assume that the output of the command above is available in the variable RETURNVALUE
if [[ $RETURNVALUE == *uploaded* ]]
then
echo "Upload successful."
else
echo "Upload failed."
fi
fi
done

谁能帮帮我?

最佳答案

我的猜测是您也可能依赖于来自 google 命令的错误代码(我假设如果上传失败它会返回错误,但您可能应该仔细检查一下)。

for f in ./*.ogv ./*.mov ./*.mp4; do
if [[ '*' != ${f:2:1} ]]; then

echo "Uploading video file $f"
if google youtube post --access unlisted --category Tech "$f" > /dev/null
then
echo "Upload successful."
else
echo "Upload failed."
fi

fi
done

一个常见的误解是 if 想要一个括号表达式来求值,这是不正确的,if 总是接受一个命令并检查错误状态;通常此命令是 [,它是 test 的别名,用于计算表达式。 (是的,如果没有优化的快捷方式使其在 bash 中运行得更快,我会感到惊讶,但从概念上讲它仍然是正确的)。

像这样通过反引号捕获输出

result=`command argument a b c`

或使用$()

result=$(command argument a b c)

但在这种情况下使用错误代码可能更好。

编辑:如果你的函数中有一个有趣的东西.. 一开始我没有注意到,但是如果你启用 nullglob shell 选项可以避免它(这将使 ./*.mov 扩展为空字符串,如果没有文件)。此外,引用 $f 否则如果您的文件名包含空格,它将中断

shopt -s nullglob
for f in ./*.ogv ./*.mov ./*.mp4; do
echo "Uploading video file $f"
if google youtube post --access unlisted --category Tech "$f" > /dev/null
then
echo "Upload successful."
else
echo "Upload failed."
fi
done

HTH.

关于bash - 想要通过将命令的输出重定向到变量来检查命令是否成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5701653/

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