This solves the problem.
echo "l=l.split('\\\n')"
Question
I'm writing a bash script and when I write the line:
echo "l=l.split('\n')"
I would like the output to actually be l=l.split('\n')
but get:
l=l.split('
')
Any idea on how to fix this? I tried using quotations at different spots and escaping the characters differently but nothing seems to be working. Appreciate the help!
**Worth noting - if I simply type the echo command into the terminal I get my desired output.. Not sure why a script is treated differently.
Solution 3
This solves the problem.
echo "l=l.split('\\\n')"
OTHER TIPS
It sounds like perhaps you got the shebang wrong (for a bash
script, anyway). Take for example:
$ cat test.sh
#!/bin/sh
echo "l=l.split('\n')"
$ ./test.sh
l=l.split('
')
$ cat test.bash
#!/bin/bash
echo "l=l.split('\n')"
$ ./test.bash
l=l.split('\n')
Even though bash
and sh
may be provided by the same shell on some systems, there are subtle differences in their behavior. If you want it to behave like it does for you in a terminal, be sure to use #!/bin/bash
.
tl;dr
If your script is really being run by bash
, then something must have turned on the off-by-default xpg_echo
shell option - either directly, or indirectly via shell option posix
.
posix
is implicitly turned on when Bash is invoked as sh
(/bin/sh
), which happens on macOS, for instance.
If your script is not being run by bash
, which is the likeliest explanation, as suggested in FatalError's helpful answer:
Ensure that your script's shebang line is either
#!/bin/bash
or #!/usr/bin/env bash
.
Alternatively, pass it directly to bash
: bash <script>
The portable solution, which shields you from variable echo
behavior, is to use printf
as follows:
printf '%s\n' "l=l.split('\n')"
In bash
, the interpretation of escape sequences such as \n
by echo
is turned OFF by default.
Option xpg_echo
must be turned on for escape sequences to be recognized by echo
.
This option is implicitly on if you run bash
in POSIX compatibility mode (verify with shopt -o posix
), which also happens if you run Bash as sh
, as is the case on macOS, for instance, where /bin/sh
is Bash.
Note that irrespective of the state of xpg_echo
by itself, you can opt into escape-sequence interpretation ad-hoc with echo -e
and opt out with echo -E
.
However, this does not work when running in POSIX compatibility mode (shopt -o posix
), where - in compliance with POSIX - echo
supports no options at all.
In other words: The following would only work if (a) your script is really being executed by bash
and (b) option posix
is off:
echo -E "l=l.split('\n')"
Again, printf
is the portable, POSIX-compliant alternative that works consistently across all POSIX-compatible shells, irrespective of the state of shell options:
# '%s\n': *without* escape-sequence interpretation
$ printf '%s\n' "l=l.split('\n')"
l=l.split('\n')
# '%b\n': *with* escape-sequence interpretation
$ printf '%b\n' "l=l.split('\n')"
l=l.split('
')