2

I am trying to call a bash function and assign the output the function returns to a variable. However, when I run the code below, I get the following error and I don't understand what I may be doing wrong:

test.sh: return: line 7: Illegal number: aGVsbG93b3JsZA== helloworld

convertfrombase64 () {
  B64DATA=$1
  echo "$B64DATA" | base64 -d
  return "$B64DATA"
}

PLAINTEXT=$(convertfrombase64 "aGVsbG93b3JsZA==")
echo "$PLAINTEXT"

1 Answer 1

5

You can't return a string from a function. A Bash function's return value follows the same rules as that of exit codes - see the related post.

You are already using the output of the function correctly. May be you want to return the exit code of base64 to indicate status, this way:

convertfrombase64 () {
  B64DATA=$1
  echo "$B64DATA" | base64 -d
  return $?
}

Based on the great suggestions got from comments, the above function could be better written as:

convertfrombase64() {
  printf '%s' "$1" | base64 -d
}

See this post for more details:

Sign up to request clarification or add additional context in comments.

3 Comments

Thank works thanks. Turns out I don't need to return anything, just want the value.
+1. Note that return $? is actually redundant, since the default behavior is to return the exit status of the last command. In fact, the function could written as just convertfrombase64 () { base64 -d <<< "$1" ; }, which also avoids touching the global B64DATA variable, avoids any nontrivial behaviors of echo, avoids some unnecessary subshells, etc.
You probably want printf '%s' "$1" | base64 -d instead of the here string, which will add a trailing newline to the value being decoded.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.