In Linux shell bash script, how to print to a file at the same line?
19,542
Solution 1
After wading through that question, I've decided that what you're looking for is echo -n
.
Solution 2
If you are looking for a single tab in between the variables, then printf is a good choice.
printf '%s\t%s' "$v1" "$v2" >> file_name
If you want it exactly like your example where the tab is padded with a space on both sides:
printf '%s \t %s' "$v1" "$v2" >> file_name
Solution 3
few options there:
-
echo -n foo bar
It's simple, but may not work on some old UNIX systems like HP-UX or SunOS. Instead the "-n" will be printed as well as the rest of the arguments followed by new line. -
echo -e "foo bar\c"
. The\c
has meaning: "produce no further output". I don't like this solution personally, but some UNIX wizards use it. -
printf %b "foo bar"
I like this solution the most. It's quite portable as well flexible.
Solution 4
Use echo -n
to trim the newline. See if that works
Related videos on Youtube

Author by
user1002288
Updated on June 04, 2022Comments
-
user1002288 6 months
In Linux shell bash script, how to print to a file at the same line ?
At each iteration,
I used
echo "$variable1" >> file_name, echo "$variable2" >> file_name,
but echo insert a newline so that it becomes
$v1 $v2
not
$v1 \tab $v2
"\c" cannot eat newline.
this post BASH shell script echo to output on same line
does not help .
thanks