简体   繁体   中英

Passing arguments values to shell script

I'm using the following script to purge cache from 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

The 1st part for cloudflare is working fine the 2nd part when I pass it to Akamai

["$urls"]

I keep getting an error and it's passing the url as an argument it returns the variable itself ($urls) not the arg value.

I ran the script as following:

sh +x  script.sh  url

Any advise here?

First i would change this:

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

$urls="$1"

Change your second curl command as the following (you need to escape the quotes):

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

Avoid creating JSON by hand like this; you can't guarantee that the resulting JSON is properly escaped. Use a tool like jq instead.

#!/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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM