I need to convert the contents of the variables as they are into base64. I decided to make a function and pass the content of the variables into it and output it later. So far I have the following
#!/bin/dash
payload1='{
"currency": "ABC",
"transaction": "1-8ef2b11f1b"
}
'
payload2='{x}'
function base64_encode() {
# must first receive the data
# ...
printf '%s' "${input}" | base64 | tr -d '=' | tr '/ ' '_-' | tr -d '\n'
}
# something like:
printf '%s' "$(printf '%s' "${payload1}" | base64_encode)"
printf '%s' "$(printf '%s' "${payload2}" | base64_encode)"
The bottom line is that I should get exactly ewogICJjdXJyZW5jeSI6ICJBQkMiLAogICJ0cmFuc2FjdGlvbiI6ICIxLThlZjJiMTFmMWIiCn0K
, not ewogICJjdXJyZW5jeSI6ICJBQkMiLAogICJ0cmFuc2FjdGlvbiI6ICIxLThlZjJiMTFmMWIiCn0
, from payload1
variable. The problem is that I don't know how to put the contents of variable in base64_encode
function.
Is there any universal way to do this? Or maybe my approach is generally wrong?
CodePudding user response:
Since you're piping data into the function, let base64 read directly from stdin:
base64_encode() {
base64 # removed questionable `tr` commands
}
CodePudding user response:
@glennjackman pointed out that you don't need arguments for your function, which is true and makes sense because you would also align with how the command base64
is meant to be used.
Here I show you how you can pass the arguments of the function base64url_encode
to the command base64
:
#!/bin/sh
payload1='{
"currency": "ABC",
"transaction": "1-8ef2b11f1b"
}
'
payload2='{x}'
base64url_encode() {
printf '%s' "$@" | base64 | tr -d '=\n' | tr '/ ' '_-'
}
payload1_b64u=$(base64url_encode "${payload1}")
payload2_b64u=$(base64url_encode "${payload2}")
printf '%s\n' "$payload1_b64u"
printf '%s\n' "$payload2_b64u"
ewogICJjdXJyZW5jeSI6ICJBQkMiLAogICJ0cmFuc2FjdGlvbiI6ICIxLThlZjJiMTFmMWIiCn0K
e3h9