Pass the entire content of the variable into a function

79 Views Asked by At

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?

1

There are 1 best solutions below

3
glenn jackman On

Since you're piping data into the function, let base64 read directly from stdin:

base64_encode() {
  base64    # removed questionable `tr` commands
}