2

I'm trying to use echo -n command to write some content to a file without a new line in node's package.json e.g

start: "echo -n hello > my.file"

When I run npm start, instead of hello without a new line, it creates -n hello in my.file. However it runs correctly in my Terminal(I'm on Mac).

3
  • Just trying to find an easy and quick way to create a file with no new line at the end. If there are other tools can do it, it's more than welcome. Commented Apr 13, 2021 at 4:59
  • Why not use your terminal directly instead of using Node.js? Commented Apr 13, 2021 at 5:14
  • @tobias, I'm combining with other commands with the newly created file. Commented Apr 14, 2021 at 0:10

2 Answers 2

1

Depending of your context, you can use printf instead of echo, which does not append a \n char automatically.

https://unix.stackexchange.com/questions/58310/difference-between-printf-and-echo-in-bash

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

Comments

1

This is due to NPM running scripts with the sh(1) shell, which does not accept the -n option. One way of solving this would be to set NPM to use Bash:

npm config set script-shell "/bin/bash"

Documentation for echo command

Some shells may provide a builtin echo command which is similar or identical to this utility. Most notably, the builtin echo in sh(1) does not accept the -n option. Consult the builtin(1) manual page.

Documentation for NPM run-scripts

The actual shell your script is run within is platform dependent. By default, on Unix-like systems it is the /bin/sh command, on Windows it is the cmd.exe. The actual shell referred to by /bin/sh also depends on the system. As of [email protected] you can customize the shell with the script-shell configuration.

Here's also a related StackOverflow answer: "echo -n" works fine when executing script with bash, but not with sh

1 Comment

I ended up with printf command. However your answer also provides very valuable information to me. Thanks

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.