bash – 要检查命令是否成功通过将其输出重定向到变量

前端之家收集整理的这篇文章主要介绍了bash – 要检查命令是否成功通过将其输出重定向到变量前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在编写一个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

有谁能够帮助我?

我的猜测是,你可以依赖于谷歌命令的错误代码(假设它返回错误,如果无法上传,但你应该仔细检查一下)。
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

一个常见的误解是,如果想要一个括号中的表达式进行评估,这不是真的,如果总是接受命令并检查错误状态;通常这个命令是[这是一个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。

原文链接:https://www.f2er.com/bash/388741.html

猜你在找的Bash相关文章