1

I am creating a kind-of alias for fast base64 encoding of strings. For it I have created following function and added it to my .bash_profile file:

# My functions
function b64() {
    perl -MMIME::Base64 -e 'print encode_base64("$1");'
}

The problem is that it encodes the string "$1" itself without processing actual value that I am "giving" to it in request:

$ b64 "test_value"
JDE=

$ echo -n "JDE=" | base64 -d
$1

I have tried using '$1' and "$1", without any quotes, but the problem persists still and it keeps encoding $1 as string and not a value.

Could you please check what am I missing here? Thanks in advance!

0

3 Answers 3

1

Apart from the obvious quoting problem that prevents the expansion of $1, you shouldn't inject data like so in your program: you should treat data as data!

Now, I'm no Perl expert, but the following should be more robust:

b64() {
    perl -MMIME::Base64 -e 'print encode_base64($ARGV[0]);' -- "$1"
}
Sign up to request clarification or add additional context in comments.

1 Comment

That's much better than my quick fix, and deserves to become the accepted answer.
0

You are using the wrong kind of quotes. You can debug this more easily if you use echo to show what you're executing:

$ b64() { echo 'print encode_base64("$1");'; }
$ b64 foo
print encode_base64("$1");
$ b64() { echo "print encode_base64('$1');"; }
$ b64 foo
print encode_base64('foo');

Other debugging techniques exist - for example printf '%q\n' or set -x.


With this knowledge, you can write your b64 as

b64() { perl -MMIME::Base64 -e "print encode_base64('$1');"; }

This gives me the expected result:

$ b64 foo
Zm9v
$ base64 -d <<<Zm9v
foo

2 Comments

Thank you very much, it did the trick. Will note these debugging tips.
Be aware that this is not robust programming: it will fail if the string contains single quotes (and, more dangerously, it is subject to arbitrary code execution).
0

You're missing the fact that single quotes inhibit expansion.

perl -MMIME::Base64 -e 'print encode_base64("'"$1"'");'

9 Comments

I have tried applying these changes. After running new ~/.bash_profile it still parses "$1" itself unfortunately: $ . ~/.bash_profile All changes were successfully applied $ b64 "test_val" JDE=
What does your code look like now?
Like this: function b64() { perl -MMIME::Base64 -e 'print encode_base64("'"$1"'");' }
And are you sure this is the function your shell is picking up?
Be aware that this is not robust programming: it will fail if the string contains double quotes (and, more dangerously, it is subject to arbitrary code execution).
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.