Closed
[Bug-Report|缺陷反馈]:代码结果获取错误 #3660
zjunAdd on  20 days agoClosed at  4 days ago
zjun
zjun
20 days ago Create

一、问题描述 (必填)

代码想获取命令结果返回值,但是此种方式获取的结果并不正确。

run_command() {
    local cmd="$*"
    echo "Executing command: $cmd"

    if ! output=$("$@" 2>&1); then
         local exit_code=$?
         echo -e "\nCommand execution failed!"
         echo -e "\nFailed command: $cmd"
         echo -e "\nError output: $output"
         echo -e "\nExit code: $exit_code"
         exit $exit_code
    fi
}

如果output是失败的,exit_code的值永远获取到0.

ops-math\install_deps.sh

二、环境信息 (可选)

A2

三、重现步骤 (可选)

示例代码如下:

zjun@119:~$ cat 1.sh 
#!/bin/bash

cmd="ls ,"                                      # 命令肯定是执行失败的
if ! out=$($cmd) 2>&1;then
    exit=$?
    echo "$? = ${exit}"
fi
zjun@119:~$ ls ,
ls: cannot access ',': No such file or directory
zjun@119:~$ 
zjun@119:~$ bash 1.sh 
ls: cannot access ',': No such file or directory
0 = 0                # 获取的到居然是0.

四、预期结果 (可选)

💡 备注(选填)

likedislike
zjunzjun
20 days ago Modify description of issue
陈思
陈思Collaborators
19 days ago Comments:

您好,感谢反馈!

问题分析

核对当前上游提交 d611059e 的 install_deps.sh,run_command 确实在 if ! output=$("$@" 2>&1) 的失败分支读取 $?。子命令失败后,! 已将条件状态取反为成功,因此此时保存的是 0,而非原始失败码;随后 exit 0 会让外层调用者把安装失败判为成功。脚本的 set -e 也不能替代这里的显式错误处理,因为命令位于条件判断中。

处理方向

一个可行方案是使用不带 ! 的 if output=$("$@" 2>&1); then … else … fi,在 else 分支进入后立即保存原始退出码,再输出诊断并按该状态退出。这样可以保留原有日志,同时正确向调用方传递失败;需关注成功命令、普通非零状态以及输出捕获的行为。

likedislike
陈思陈思Collaborators
19 days ago Assign chensi79 as responsible person
陈思陈思Collaborators
19 days ago Added label: pending-confirmation
陈思陈思Collaborators
19 days ago Removed label: pending-confirmation
陈思陈思Collaborators
19 days ago Removed responsible person chensi79
陈思陈思Collaborators
19 days ago Assign songkai111 as responsible person
陈思陈思Collaborators
19 days ago Added label: pending-confirmation
陈思陈思Collaborators
19 days ago Removed label: pending-confirmation
gaopengcheng521gaopengcheng521
5 days ago Associated pull request
CANN-robotCANN-robotCollaborators
4 days ago Close issue
CANN-robotCANN-robotCollaborators
4 days ago Added label: resolved