Home > Software design >  Cron removing $ character from environment variable in shell script
Cron removing $ character from environment variable in shell script

Time:10-22

I have an environment variable in a docker container that stores a password with special characters. This particular password contains a $ in it. I output this environment variable in a shell script. If I run the script manually, everything is fine. When the cron runs the script, the $ and the following 2 characters are removed. I have tried escaping the special characters in several ways, the latest of which is below, but the outcome is the same (fine manually, missing with the cron). For this example, assume the password is blahblah$xy*blahblah, which is what I would see when running the script. If the cron runs the script, I would get blahblah*blahblah.

My script (testVars.sh):

#!/bin/bash

echo "Testing variables"

MY_PASS=$MY_PASSWORD
TEST_PASS=$(sed -e 's/[^a-zA-Z0-9,._ @%/-]/\\&/g; 1{$s/^$/""/}; 1!s/^/"/; $!s/$/"/' <<< $MY_PASSWORD)

echo ${MY_PASS}
echo ${TEST_PASS}

My cron:

BASH_ENV=/root/env_vars.sh
33 13 * * * root /opt/testVars.sh >> /opt/cron.log

I am assuming that it is actually possible to have a $ sign in a string in this way.

CodePudding user response:

I solved it by added the following into the docker-entrypoint.sh file, just before my printenv command:

export MY_PASSWORD=$(sed -e 's/[^a-zA-Z0-9,._ @%/-]/\\&/g; 1{$s/^$/""/}; 1!s/^/"/; $!s/$/"/' <<<"$MY_PASSWORD")

Thanks to Ture Pålsson for pointing me in the right direction.

  • Related