我怎样才能重构这个bash脚本?

时间:2017-12-16 19:21:19

标签: json bash curl

exportsData=$(curl -X GET \
 -H 'Accept: application/vnd.xxxxx+json; version=3.0' \
 -H 'Authorization: Bearer RCexxxxxxxxxxxxxxxxxxxxxxxxxcVefI5mWy' \
 -H 'Content-Type: application/json' \
https://api.xxxx.com/apps/9xxxxxxxxx15f96fe/exports)
status=$(echo $exportsData | jq '.[0].status')
downloadURL=$(echo $exportsData | jq '.[0].download_url') 
export ENCRYPTED_AES_KEY=$(echo $exportsData | jq '.[0].encrypted_aes_key')
export AES_IV=$(echo $exportsData | jq '.[0].aes_iv')

export ENCRYPTED_TARBALL=encryptedChatDump.tar.gz.enc
$(curl -X GET -o ENCRYPTED_TARBALL \
 -H 'Accept: application/vnd.xxxxx+json; version=3.0' \
 -H 'Authorization: Bearer RCexxxxxxxxxxxxxxxxxxxxxxxxxcVefI5mWy' \
 -H 'Content-Type: application/json' \
https://storage.googleapis.com/someUrlWhereTheFileIsBeingDownloadedFrom)

export OUTPUT_TAR=finalChatDumpUnencrypted.tar.gz
export PRIVATE_KEY_PATH=~/.ssh/id_rsa


openssl enc -in $ENCRYPTED_TARBALL -out $OUTPUT_TAR -d -aes-256-cbc |   base64 --decode | openssl rsautl -decrypt -inkey $PRIVATE_KEY_PATH | base64   --decode 

这是我的第一个脚本,我很难写出最短的代码。

1 个答案:

答案 0 :(得分:3)

你可以在循环中处理变量:

for key in status download_url encrypted_aes_key aes_iv
do
    val=$(echo "${exportsData}" | jq ".[0].${key}")
    echo "${val}"
done

编辑:

为了存储变量以进行进一步的“处理”,您可以在do循环中显式创建它们:

for key in status download_url encrypted_aes_key aes_iv
do
    val=$(echo "${exportsData}" | jq ".[0].${key}")
    declare -x "$(echo ${key} | tr '[a-z]' '[A-Z]')"="${val}"
done

这将创建(并导出)大写变量STATUSDOWNLOAD_URL等。