gpt4 book ai didi

linux - bash 隐藏默认的 stderr 代码并将其替换为我自己的

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:50:08 26 4
gpt4 key购买 nike

当我使用 ping foo.com 时,我得到响应或 ping: unknown host foo.com我正在使用此脚本来显示自定义响应

status=$(ping -c 1 foo.com 2> /dev/null)

if [[ status -ne '200' ]]; then
echo "site found"
else
echo "site not found"
fi

上面的问题是,如果找到网站,我会收到 找到网站 响应,但如果没有,我会收到默认的 ping: unknown host foo,而不是错误消息。 com

已更新。

declare -A websites 
websites=("" "")
function ping_sites(){
if [[ $1 != 'all' ]]; then
status=$(curl -I --stderr /dev/null $1 | head -1 | cut -d' ' -f2)
result=$(ping -c 1 $1 | grep 'bytes from' | cut -d = -f 4 | awk {'print $1'} 2> /dev/null)

if [[ status -ne '200' ]]; then
echo -e "$1 $c_red \t $status FAIL $c_none"
else
echo -e "$1 $c_green \t $status OK $c_none"
fi
else
...

.

ping all 
ping foo.com

最佳答案

pingWrap(){
if ping -c 1 "$1" >/dev/null 2>&1; then
echo "site found"
else
echo "site not found"
fi
}
pingWrap foo.com
pingWrap localhost

if ping -c 1 "$1">/dev/null 2>&1; then 抑制所有输出和测试ping 命令的返回状态,它是 0(成功)或其他(失败)。

[[ status -ne '200' ]] 获取字符串 status 和字符串 200,将每个字符串转换为整数并进行测试不等式的两个整数,这听起来很荒谬。

shell 命令的返回状态保存在 $? 变量中,它与 HTTP 返回码无关。 HTTP 在 TCP 之上运行,而 ping 甚至不使用 TCP。


HTTP 状态

如果目标站点已启动并使用 HTTP,您可以通过以下方式在标准输出上获取 http 状态:

httpStatus(){ curl -s -w %{http_code} "$@" -o /dev/null; }

例如,

httpStatus google.com #200
httpStatus google.com/secret #301

st="`httpStatus "$1"`" &&
case "$st" in
301) echo Moved permanently;;
200) echo Success;;
*) echo Unknown;;
esac

关于linux - bash 隐藏默认的 stderr 代码并将其替换为我自己的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33964730/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com