My shell is dash. My problem is the following:
# A="abc\nde fg"
# printf "$A"
abc
de fg#
# B="abc\\nde fg"
# printf "$B"
abc
de fg#
# C="abc\\\nde fg"
# printf "$C"
abc\nde fg#
The string variable I'm working with has both spaces and \n
and possibly other whitespace characters. I would like to access the variable $A
without escaping the \n
in the string. Using single quotes would not interpret it as a variable and using double quotes interprets those special characters.
Does dash have a way built in to the shell to do so? I know I can send the variable to an external program that will double the backslashes for the escape characters in the string, but that just feels wrong.
EDIT:
I realize my mistake with printf
but it's unrelated in this case. Initially I was using echo
. This is a better example of what I'm asking. Here are two of the exact same command sequences, only the first is in bash and the second is in dash:
bash
$ cat sample.txt
abc\nde fg
some string
$ A=`cat sample.txt`
$ echo "$A"
abc\nde fg
some string
$
dash
$ cat sample.txt
abc\nde fg
some string
$ A=`cat sample.txt`
$ echo "$A"
abc
de fg
some string
$
I would like to know if I can have dash not interpret the \n
in this sequence of commands. I have already implemented a workaround using an external command. The proper use of printf
does what I want, but I'm curious to see if the dash shell itself has some way of doing this its own.
Here's the reason the question came up, for completeness. I need to read a file and CONDITIONALLY comment or uncomment the bottom part. The first part has a literal \n
(not newline) that needs to stay that way in the rewritten file.
I split the file into 2 pieces using sed enclosed in backticks and assign those to variables. At the end I concatenate the variables by simply doing something like "$VAR1$VAR2"
, where $VAR2
has already been conditionally commented, uncommented, or left alone.
A
then you can use"$A"
to get the value of that variable. A variable expansion inside double quotes does not interpret special characters. If that doesn't do what you want then the problem is in a part that you haven't told us about.echo
behave differently. If you don't like dash'secho
, perhaps/bin/echo
is more to your taste?type echo
is what tells you it's a builtin command (though you still have to realise that it's two different builtins).which echo
will always search the path and doesn't know about shell builtins.