Your Python one-liner works just fine as-is; the problem is your test. No matter how you set the variable, you won't see its value properly in your hexdump unless you quote its expansion, like this:
$ printf '%s' "$GREENIE" | hexdump
0000000 0a 0d 0a 0d 0a 0d 0a 0d
0000008
(I used printf
instead of echo
to avoid confusion, since echo
adds an extra newline on the end, which shows up in the output of hexdump
even though it's not part of the value of $GREENIE
. I could also have used echo -n
since this is a bash-specific question, but I try to avoid that since it's not part of POSIX.)
Without the quotes, the shell does word-splitting on the newlines, so you get nothing but the carriage returns back from printf
:
$ printf '%s' $GREENIE | hexdump
0000000 0d 0d 0d 0d
0000004
If you use echo
instead (with bash's -n
option to avoid the confusing extra newline), it just joins those carriage-returns back together with the default separator (space):
$ echo -n $GREENIE | hexdump
0000000 0d 20 0d 20 0d 20 0d
0000007
You could also use shell built-ins to generate the string, although it doesn't have a convenient string-multiplier operator. You can use a dumb for loop:
GREENIE=$(for ((i=0;i<4;++i)); do printf '\n\r'; done)
But it's short enough that you can just type it out:
GREENIE=$(printf '\n\r\n\r\n\r\n\r')
If we're being bash-specific, you could use ANSI strings and skip the printf
:
GREENIE=$'\n\r\n\r\n\r\n\r'
or combine them and get cute with brace-expansion:
GREENIE=$(printf '%s' $'\n\r'{,,,})
Either way, if you are just using the variable inside a shell script, you don't need to export
it to the environment; that's only for making it accessible to other programs:
$ GREENIE=hello
$ echo $GREENIE
hello
$ python -c 'import os; print os.getenv("GREENIE")'
None
$ export GREENIE
$ python -c 'import os; print os.getenv("GREENIE")'
hello
You can also export a variable into the environment of a particular program without setting it in the shell at all, by placing the assignment on the command line where you run the program:
$ unset GREENIE
$ echo $GREENIE
$ GREENIE=hello python -c 'import os; print os.getenv("GREENIE")'
hello
$ echo $GREENIE
$
And if you're not exporting it to the environment, the usual convention is to give it a lowercase name:
$ greenie=hello
$ echo $greenie
hello