shell脚本输入不适用于npm init

时间:2017-07-19 22:50:44

标签: bash shell npm

我正在学习在终端中编写shell脚本。我试图自动化npm init进程,只是为了练习。所以我从终端读入所有参数,然后尝试用它们自动执行npm init。但是,当npm init要求输入点时,该过程始终会中止。其他任何地方只需留下一个空行来模拟输入键按下,或使用该变量工作正常。为什么它会在那时退出?

read -p "Project name: " name;
read -p "Version: " version;
read -p "Project description: " description;
read -p "Entry point: " entryPoint;
read -p "Test command: " testCommand;
read -p "Git repository: " gitRepo;
read -p "Keywords: " keywords;
read -p "Author: " author;
read -p "License: " license;
read -p "Is this okay?: " isOkay;

npm init <<!
$name
$version
$description
$entryPoint
$testCommand
$gitRepo
$author
$license
$isOkay
!

运行脚本时的终端输入和结果:

Project name: name
Version: 1.0.0
Project description: description
Entry point: app.js
Test command: 
Git repository: 
Keywords: 
Author: Author
License: ISC
Is this okay?: yes
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg> --save` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
name: (node) name
version: (1.0.0) 1.0.0
description: description
entry point: (index.js)

就是这样。它每次都在入口处退出。

1 个答案:

答案 0 :(得分:0)

我不知道为什么这不起作用,但程序可以在不直接使用stdin的情况下读取用户输入。 npm可能属于这一类。

对于这种情况,将文本传递给提示的解决方案是使用expect命令。

read -p "Project name: " name;
read -p "Version: " version;
read -p "Project description: " description;
read -p "Entry point: " entryPoint;
read -p "Test command: " testCommand;
read -p "Git repository: " gitRepo;
read -p "Keywords: " keywords;
read -p "Author: " author;
read -p "License: " license;
read -p "Is this okay?: " isOkay;


/usr/bin/expect <<!

spawn npm init
expect "package name:"
send "$name\n" 
expect "version:"
send "$version\n" 
expect "description:"
send "$description\n" 
expect "entry point:"
send "$entryPoint\n" 
expect "test command:"
send "$testCommand\n" 
expect "git repository"
send "$gitRepo\n" 
expect "keywords:"
send "$keywords\n" 
expect "author:"
send "$author\n" 
expect "license:"
send "$license\n" 
expect "Is this ok?"
send "$isOkay\n"
expect eof
!
echo "DONE!"