Issue
I just wann write a very basic script, which
- inits npm in a new project folder
- Installs nodemon
- creates an index.js file
- adds a start command into the package.json for nodemon
- writes "console.log" into the index.js file
I seem to be close, but adjusting the package.json does not work. Somehow the search variable is two time in ...
I want to achive:
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon my_file.js"
I achive:
"test": "echo \"Error: no test specified\" "test": "echo \"Error: no test specified\" && exit 1""test": "echo \"Error: no test specified\" && exit 1" exit 1","start": "nodemon my_file.js"
Full code
#!/bin/bash -e
set -e
clear
# Init npm
npm init -y && npm i --save-dev nodemon && touch index.js
wait
# find test command
constToFind='\"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"'
# add nodemon command (with comma, line break and tab)
replacement=',\n\t\"start\": \"nodemon my_file.js\"'
combineReplacement="${constToFind}${replacement}"
# Add start command to package.json
sed -i "s/$constToFind/$combineReplacement/g" package.json
# Create entry javascript file with console.clear on tops
echo "console.clear();" >> index.js
Solution
Instead of substituting you can append with the sed a
command:
$ addon='\"start\": \"nodemon my_file.js\"'
$ sed "/$constToFind/a\
$addon
" package.json
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon my_file.js"
(if you care your package.json
file use the -i
only after you checked that it really works as expected).
And if your sed
version supports the alternate syntax this is a bit simpler:
$ addon='\"start\": \"nodemon my_file.js\"'
$ sed "/$constToFind/a$addon" package.json
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon my_file.js"
Answered By - Renaud Pacalet Answer Checked By - Timothy Miller (WPSolving Admin)