Linux 上的 bash 命令在捕获错误消息时不起作用

问题描述 投票:0回答:1

我尝试从像这样的变量中的命令捕获错误消息,

# /dir1/dir2 exists so this command will succeed
errMsg=$(cd /dir1/dir2 2>&1)

# get 0 as expected
echo $?

# shows that I am still in the original directory not /dir1/dir2
pwd

$(cd /dir1/dir2 2>&1)
替换右侧会得到相同的结果。

这是否意味着我无法从 shell 命令捕获错误消息?

bash unix
1个回答
0
投票

cd
放入包装器中,尝试在捕获输出的子 shell 中再次运行它,可能如下所示:

# wrapper sets a variable cdError with stderr content
cd() {
  local rc
  if builtin cd "$@"; then
    cdError=
    return
  else
    rc=$?
    cdError=$(builtin cd "$@" 2>&1)
    return "$rc"
  fi
}

也就是说,我质疑你为什么要这样做。

cd /somewhere || exit
足以满足大多数常见用例。

© www.soinside.com 2019 - 2024. All rights reserved.