0

I'm using a bash script to send an argument to a node app like so:

testString="\nhello\nthere"
node ./myNodeScript.js $testString

The trouble comes when I use testString inside the node program after capturing it as process.argv[2] -- rather than expand the \n characters to newlines node prints them literally. I need a way to tell node to convert the argument to a javascript string, respecting the formatting characters. Is there a way to go about this?

2 Answers 2

1

Try to avoid confusing literal linefeeds and literal backslash followed by literal n.

If you want the string you pass to have linefeeds, you should ignore JavaScript string literal syntax and just pass the linefeeds as linefeeds:

$ cat myNodeScript.js
console.log("Node was passed this: " + process.argv[2])

$ cat myBashScript
testString='
hello
there'
printf 'Bash passes this: %s\n' "$testString"
node myNodeScript.js "$testString"

$ bash myBashScript
Bash passes this: 
hello
there
Node was passed this: 
hello
there

Arguments should contain data (linefeed) while script files should contain code (quoted linefeed or expanded \n as appropriate in the language). When you make sure not to confuse code and data, you can trivially handle both backslash-en and linefeeds in the same string with no surprises:

testString='
"\nhello\nthere" is JavaScript syntax for:
hello
there'

There are ways to express this on a single line in bash using \n for linefeeds and \\n for backslash-en, you just need to make sure that it remains as code, and doesn't accidentally make it into the variable as data.

Sign up to request clarification or add additional context in comments.

Comments

0

Can you try this:

testString=$( printf "\nhello\nthere")
node ./myNodeScript.js "$testString"

And let me know if it works?

1 Comment

unfortunately it didn't add newlines.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.