0

I am in a situation that can not find a solution for my case.

I need to run a long command in bash, say:

node -p "const db = {1:1, 2:2};Object.keys(db).sort((a, b)=> a-b).map(Number).filter((n) => {return !isNaN(n)})"

Due to this command is relative long, I tried to use \ to wrap my command. Like this:

node -p "const db = {1:1, 2:2};Object.keys(db)\
.sort((a, b)=> a-b).map(Number).filter((n) => {return !isNaN(n)})"

But it complained that

bash: !isNaN: event not found

which I find similar to this question

So I tried to replace " with ':

node -p 'const db = {1:1, 2:2};Object.keys(db)\
.sort((a, b)=> a-b).map(Number).filter((n) => {return !isNaN(n)})'

But this time, \ is considered part of the command which is actually meaningless because I just want to wrap my command.

How can I solve this delemma?

Kusalananda
  • 333,661
krave
  • 103
  • You can temporarily turn off history expansion with set +o histexpand or set +H. – Deathgrip Feb 13 '22 at 20:59
  • Does that code need to be passed as one line? I mean, if you use single quotes and remove the backslash, the string node gets would just have the newline right where it is, and you could just wrap the code in any way that works for the actual parser. – ilkkachu Feb 13 '22 at 21:10
  • @ikk The code can be passed as several lines but which means I need to enter node REPL which is another environment instead bash. – krave Feb 14 '22 at 07:13

1 Answers1

2

Use a combination of single and double quotes, or just put the \! outside the quotes. In general using single quotes causes less surprises.

node -p "const db = {1:1, 2:2};Object.keys(db)\
.sort((a, b)=> a-b).map(Number).filter((n) => {return "\!"isNaN(n)})"

node -p "const db = {1:1, 2:2};Object.keys(db)
.sort((a, b)=> a-b).map(Number).filter((n) => {return "'!'"isNaN(n)})"

node -p 'const db = {1:1, 2:2};Object.keys(db)'
'.sort((a, b)=> a-b).map(Number).filter((n) => {return !isNaN(n)})'

icarus
  • 17,920