2017-07-19 94 views
0

我正在学习在终端中编写shell脚本。我试图自动化npm init进程,只是为了练习。所以我从终端读入所有参数,然后尝试自动执行一个npm init与他们。然而,当npm init要求入口点时,该过程总是中止。其他任何地方,只要留下一个空行来模拟一个输入键按下,或使用该变量工作正常。为什么在那个时候退出?Shell脚本输入不适用于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) 

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

回答

0

我不知道为什么这不起作用,但程序可以直接使用标准输入读取用户输入。 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!" 
+0

有趣。这工作 - 谢谢。 ''spawn npm init'后面有大约10秒的延迟。任何想法为什么? – cweber105