【问题标题】:unable to comare the output of the function in shell script [duplicate]无法比较shell脚本中函数的输出[重复]
【发布时间】:2020-12-13 19:44:01
【问题描述】:

我正在尝试删除 docker 容器并存储或比较结果,但我无法做到这一点,请告诉我如何获取返回值以进行进一步处理

delete_the_container() {

 res= docker container rm -f $1 && echo "success" || echo "fail"
 echo "$?"

}

fielpos="./filename"

input="./filename"

while IFS= read -r line
do
   #echo "$line"

   res= $(delete_the_container $line)

   echo "$res"                  #not get the res value    

done < "$input"

【问题讨论】:

    标签: bash


    【解决方案1】:

    $? 返回最后一条命令的代码值,下面的代码一定能帮到你

    docker container rm -f $1
    if [[ $? == 0 ]]; then 
         ... code if rm command success ...
    else
         ... code if rm command failed...
    fi
    

    你的行(我添加了 $(...) 来执行命令):

    res= $(docker container rm -f $1 && echo "success" || echo "fail")
    

    res 值可以是“成功”或“失败”,但 $? 始终为 1,因为最后一个命令是 echo

    【讨论】:

      猜你喜欢
      • 2015-12-03
      • 2016-01-16
      • 1970-01-01
      • 2016-03-12
      • 1970-01-01
      • 1970-01-01
      • 2013-12-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多