If the objective is specifically to write a newline and an x
(and another newline?) to a file,
without having n
and x
appear consecutively (i.e., nx
)
in your command
(and without including an undesired space in your output),
a very simple approach is
{ echo; echo "x";} >> file
(to write newline, x
, newline), or
{ echo; echo -n "x";} >> file
(to write newline and x
, but no newline at the end).
You can also use parentheses instead of braces for grouping:
(echo; echo "x") >> file
Note that, with braces, you must have whitespace
(space(s), tab(s) and/or newline(s)) after the opening {
,
and you must have a ;
(and/or newline(s)) before the closing }
.
Or you can do two totally separate (not grouped) commands
that do redirection independently:
echo >> file
echo "x" >> file
Or use Jesse_b’s answer:
printf '\n%s\n' 'x' >> file
(to write newline, x
, newline), or
printf '\n%s' 'x' >> file
(to write newline and x
, but no newline at the end).
But if the objective is more general —
to write a bunch of strings (with no intervening spaces),
while separating them by spaces on the command line, consider
printf '%b' string …
where %b
is the conversion format to print a string
with \
sequences interpreted (in contrast to %s
,
which prints strings literally).
For example,
printf '%b' '\n' foo '\t' bar
will write newlinefoo
tabbar
;
i.e.,
foo bar
(with no newline at the end).
You could also say
printf '%b%b%b%b' '\n' foo '\t' bar
but you don’t need to;
the format will be applied as many times as necessary
to display all the arguments.
Therefore, if you want to add a newline at the end,
printf '%b\n' '\n' foo '\t' bar
will not work; it will add a newline after each argument.
You can do
printf '%b' '\n' foo '\t' bar '\n'
(adding a newline as a final argument), or
printf '%b%b%b%b\n' '\n' foo '\t' bar
(counting the arguments), or
{ printf '%b' '\n' foo '\t' bar; echo;}
Yet another approach, if you’re using bash, is
printf '%s' $'\n' foo $'\t' bar
using bash’s $'text…'
notation
to interpret \
sequences.
Applying this to the original question, we would get
printf '%s' $'\n' x
echo -e "\n x"
? – RomanPerekhrest Feb 07 '18 at 12:29x
in the second line... I don't want that single space beforex
. I want space only in the command itself for ease of read. – Arcticooling Feb 07 '18 at 13:06{ echo; echo x; } >file
. – Kusalananda Feb 07 '18 at 13:17