Linux Shell如何获取各个管道的返回码&Bash Ubuntu CentOS PIPESTATUS curl grep

问题

当我们在linux shell(如bash)中使用管道执行多个命令时,$?只能获取到最后一条命令的返回码,那么应该怎么获取管道前面的命令的返回码呢,请看下文:

当执行一条管道命令时,linux会使用PIPESTATUS这个数组变量来保存每个管道的返回码。PIPESTATUS[0]表示管道中第一个命令的返回码,PIPESTATUS[1]表示第二个命令的返回值,这是一个共享的变量,为避免别的命令改变它的内容,可以将它复制到一个新的数组。

bash 复制代码
#!/bin/bash
echo "tftf"
true | false | true | false
RC=( "${PIPESTATUS[@]}" )
echo "RC[0] = ${RC[0]}"        # true = 0
echo "RC[1] = ${RC[1]}"        # false = 1
echo "RC[2] = ${RC[2]}"        # true = 0
echo "RC[3] = ${RC[3]}"        # false = 1

echo "ftft"
false | true | false | true
RC=( "${PIPESTATUS[@]}" )
echo "RC[0] = ${RC[0]}"        # false = 1
echo "RC[1] = ${RC[1]}"        # true = 0
echo "RC[2] = ${RC[2]}"        # false = 1
echo "RC[3] = ${RC[3]}"        # true = 0

echo "fftt"
false | false | true | true
RC=( "${PIPESTATUS[@]}" )
echo "RC[0] = ${RC[0]}"        # false = 1
echo "RC[1] = ${RC[1]}"        # false = 1
echo "RC[2] = ${RC[2]}"        # true = 0
echo "RC[3] = ${RC[3]}"        # true = 0

执行上面的bash文件,输出如下所示:

bash 复制代码
jagitch@jagitch-MS-7B93:~$ source pipeline.sh
tftf
RC[0] = 0
RC[1] = 1
RC[2] = 0
RC[3] = 1
ftft
RC[0] = 1
RC[1] = 0
RC[2] = 1
RC[3] = 0
fftt
RC[0] = 1
RC[1] = 1
RC[2] = 0
RC[3] = 0

一个具体的实例

bash 复制代码
#!/bin/bash
WEB_SERVER=steve-parker.org
curl -# -f -u ${USERNAME}:${PASSWORD} http://${WEB_SERVER}/ | grep "SomeMessage"
RC=( "${PIPESTATUS[@]}" )
if [ "${RC[0]}" -eq "22" ]; then
  # curl returned 22, indicating some error above 400,
  # such as: 404 Not Found, 401 Unauthorized, etc.
  echo "Invalid credentials"
  exit 1
fi

# PIPESTATUS has gone, but we can still inspect RC
if [ "${RC[1]}" -eq "0" ]; then
  echo "Grep succeeded"
  echo "Web server reported SomeMessage"
else
  echo "Web server didn't report SomeMessage"
fi

推荐阅读

1. 使用树梅派搭建Golang、Python、NodeJs的开发服务器

2. 教你如何1秒安装一个Linux系统(ubuntu,debian,centos) 比虚拟机安装系统省时省心省力

3. 超级详细的Github双重验证开启教程&github Two-factor authentication

相关推荐
watermelonoops1 小时前
Deepin和Windows传文件(Xftp,WinSCP)
linux·ssh·deepin·winscp·xftp
疯狂飙车的蜗牛2 小时前
从零玩转CanMV-K230(4)-小核Linux驱动开发参考
linux·运维·驱动开发
远游客07134 小时前
centos stream 8下载安装遇到的坑
linux·服务器·centos
马甲是掉不了一点的<.<4 小时前
本地电脑使用命令行上传文件至远程服务器
linux·scp·cmd·远程文件上传
jingyu飞鸟4 小时前
centos-stream9系统安装docker
linux·docker·centos
超爱吃士力架5 小时前
邀请逻辑
java·linux·后端
White_Mountain6 小时前
在Ubuntu中配置mysql,并允许外部访问数据库
数据库·mysql·ubuntu
cominglately7 小时前
centos单机部署seata
linux·运维·centos
魏 无羡7 小时前
linux CentOS系统上卸载docker
linux·kubernetes·centos
coder_pig7 小时前
📝小记:Ubuntu 部署 Jenkins 打包 Flutter APK
flutter·ubuntu·jenkins