要获取管道中 ls
命令的返回值(退出状态码),可以使用以下方法:
在 Bash 中(推荐)
Bash 提供了 PIPESTATUS
数组,用于存储管道中每个命令的退出状态:
ls | tee 1.txt exit_status_ls=${PIPESTATUS[0]} # 获取 ls 的退出状态 exit_status_tee=${PIPESTATUS[1]} # 获取 tee 的退出状态# 检查结果 echo "ls 的返回值: $exit_status_ls" echo "tee 的返回值: $exit_status_tee"