将参数值传递给shell脚本

时间:2017-06-19 09:32:24

标签: bash shell

我使用以下脚本从cdn中清除缓存,

#!/bin/bash

##  API keys ##
zone_id=""
api_key=""
login_id=""
akamai_crd=""

## URL ##

urls="$1"
[ "$urls" == "" ] && { echo "Usage: $0 url"; exit 1; }

echo "Purging $urls..."

curl -X DELETE "https://api.cloudflare.com/client/v4/zones/${zone_id}/purge_cache" \
     -H "X-Auth-Email: ${login_id}" \
     -H "X-Auth-Key: ${api_key}" \
     -H "Content-Type: application/json" \
     --data "{\"files\":[\"${urls}\"]}"

#echo "CF is done now purging from Akamai ..."

echo  "..."

curl -v -s https://api.ccu.akamai.com/ccu/v2/queues/default -H "Content-Type:application/json" -d '{"objects":["$urls"]}' -u $akamai_crd

当我将它传递给Akamai时,第二部分cloudflare正常工作

["$urls"]

我一直收到错误并且它将url作为参数传递,它返回变量本身($ urls)而不是arg值。

我按照以下方式运行脚本:

sh +x  script.sh  url

这里有任何建议吗?

2 个答案:

答案 0 :(得分:1)

首先我会改变这个:

SCRIPTNAME=$(basename "$0") 
...
if [ $# != 1 ] then 
    echo "Usage: $SCRIPTNAME url" 
    exit 
fi 

$urls="$1"

更改第二个curl命令,如下所示(您需要转义引号):

--data "{\"files\":[\"${urls}\"]}"

答案 1 :(得分:1)

避免像这样手工创建JSON;您无法保证生成的JSON已正确转义。请改用jq之类的工具。

#!/bin/bash

##  API keys ##
zone_id=""
api_key=""
login_id=""
akamai_crd=""

## URL ##

url=${1:?Usage: $0 url}

headers=(
  -H "X-Auth-Email: $login_id"
  -H "X-Auth-Key: $api_key"
  -H "Content-Type: application/json"
)

purge_endpoint="https://api.cloudflare.com/client/v4/zones/${zone_id}/purge_cache"

echo "Purging $url..."

jq -n --arg url "$url" '{files: [$url]}' | 
  curl -X DELETE "$purge_endpoing" "${headers[@]}" --data @-

#echo "CF is done now purging from Akamai ..."

echo  "..."

jq -n --arg url "$url" '{objects: [$url]}' | 
  curl -v -s -H "Content-Type:application/json" -d @- -u "$akamai_crd"