linux / Bash从curl输出中提取变量

时间:2018-04-05 22:00:41

标签: linux bash shell curl centos

此脚本可直接从命令行测试Internet速度:

curl -s https://raw.githubusercontent.com/sivel/speedtest-cli/master/speedtest.py | python -

Retrieving speedtest.net configuration...
Testing from XXXX (X.X.X.5)...
Retrieving speedtest.net server list...
Selecting best server based on ping...
Hosted by XXXX (XX) [0.54 km]: 3.513 ms
Testing download speed................................................................................
Download: 191.68 Mbit/s
Testing upload speed................................................................................................
Upload: 154.36 Mbit/s

我知道我可以使用| grep Download/Upload

获取下载或上传行

但是如何将下载和上传转换为变量?

2 个答案:

答案 0 :(得分:1)

一次性拍摄:

mapfile -t speeds < <(
    curl -s https://raw.githubusercontent.com/sivel/speedtest-cli/master/speedtest.py | 
    python - | 
    grep -oP '(Up|Down)load: \K[\d.]+'
)
echo "Down: ${speeds[0]}"
echo "Up: ${speeds[1]}"

答案 1 :(得分:0)

# save your value *once*
result=$(curl ...)

# ...then you can search through it multiple times.
if [[ $result =~ 'Download: '([[:digit:].]+)' Mbit' ]]; then 
    download_speed=${BASH_REMATCH[1]}
fi
if [[ $result =~ 'Upload: '([[:digit:].]+)' Mbit' ]]; then 
    upload_speed=${BASH_REMATCH[1]}
fi

echo "Test results: Download speed ${download_speed:-unknown}"
echo "              Upload speed ${upload_speed:-unknown}"