Ben Carlson
Ben Carlson

Reputation: 1255

Stop inserting newline before comma

I have a bash script running on MacOS Catalina. The script appends lines to a csv file, but something seems to be inserting new lines before the comma.

In the script, when I successfully complete a step, I want to log this in the csv by adding the id and the word "success".

log=results.log
id=474651680

echo $id,success >> $log

I want the file to contain:

474651680,success

But instead the file contains:

474651680
,success

I can't figure out why this newline is being inserted.

Upvotes: 0

Views: 96

Answers (2)

pepoluan
pepoluan

Reputation: 6780

There's definitely a newline in id

Strip it using bash's "suffix removal" and "ANSI-C quoting" features:

echo "${id%$'\n'},success" >> $log

Explanation:

  • ${id} same as $id
  • $'\n' converts the string "\n" to newline
  • ${id%suffix} outputs $id with suffix removed

Upvotes: 2

Rob Evans
Rob Evans

Reputation: 2874

Try adding

set -e # exit on erro
set -x # show debug level info in console

You will then be able to see what's going on behind the scenes when running your script in the terminal.

Also try using: "${variableName}" rather than just $variableName

In your case I'd try:

echo "${id},success" >> $log

Also it seems likely there's a new line being included as part of the variable you're setting as id. Chances are it could be your editor doing this.

Upvotes: 2

Related Questions