I am trying to get my tunnel ID from sauce labs... To get this I am doing the following:
SAUCE_TUNNELL_IDENTIFIER=$(curl https://saucelabs.com/rest/v1/myusername/tunnels -u myusername:mykey)
This returns ["my-tunnel-id"]
So I want to get rid of the [] and export my tunnel id..
Here is the export and removal of []
export SAUCE_TUNNELL_IDENTIFIER=$(echo $SAUCE_TUNNELL_IDENTIFIER | awk '{print substr($0, 2, length($0) -2)}')
When I do an export -p
, I see it like this "\"my-tunnel-id\""
But if I just do an echo $SAUCE_TUNNELL_IDENTIFIER
, I do not see the exta "\
in my variable. Where is this coming from? Also, any help making this into one better command would also be appreciated! :)
The server is returning a JSON array; you could use something like jq
to extract just the single element in the array, but for something this simple, you can just use parameter expansion.
$ SAUCE_TUNNELL_IDENTIFIER=$(curl https://saucelabs.com/rest/v1/myusername/tunnels -u myusername:mykey)
$ SAUCE_TUNNELL_IDENTIFIER=${SAUCE_TUNNELL_IDENTIFIER//[]\"[]}
$ echo "$SAUCE_TUNNELL_IDENTIFIER"
my-tunnel-id
Update:
I assumed the identifier could not contain brackets or quotes. A safer, though longer, alternative is to strip each outer character one by one.
$ STI=$(curl ...)
$ STI=${STI#[}
$ STI=${STI#\"}
$ STI=${STI%]}
$ STI=${STI%\"}
and at this point I may as well show how to use jq
to do this:
$ curl ... | jq -r '.[0]'
my-tunnel-id
.
represents the incoming JSON; [0]
extracts the first element; -r
tells jq
to output the raw string instead of the quoted JSON string (my-tunnel-id
instead of "my-tunnel-id"
).