简体   繁体   English

从文本文件中读取输入,Bash 脚本

[英]Reading in input from text file, Bash script

I am new to writing scripts in Bash and I am working on an assignment to make an inventory system.我是在 Bash 中编写脚本的新手,我正在完成一项任务来制作库存系统。 I have written all the scripts and they all work from using the standard input terminal.我已经编写了所有脚本,它们都使用标准输入终端工作。 I now am looking to take the inputs from a text file called a1Input.txt which has all inputs on a new line.我现在希望从名为 a1Input.txt 的文本文件中获取输入,该文件在新行中包含所有输入。

r
9823
r
5430
c
7777
sml_widget
Small Widget (1 oz.)
6.99
15
50
Small, white, widget w/o packaging
r
7777
d
9823
r
9823
r
3293
u
3293


29.99
33
75


r
3293


The code for my initial bash script is this我的初始 bash 脚本的代码是这样的

#!/bin/bash

# assign1.bash

shopt -s nocasematch

option=""
until [ "$option" = "F" ]; do
echo "C - create a new item"
echo "R - read an existing item"
echo "U - update an existing item"
echo "D - delete an existing item"
echo "T - total price of an item"
echo "Choose a option"
read option
case $option in
C)
./create.bash
;;R)
./read.bash
;;U)
./update.bash
;;D)
./delete.bash
;;T)
./total.bash
;;*) 
echo "Invalid input"



esac
done


What i would do to inject inputs from file to an interactive script is just:将文件中的输入注入到交互式脚本中我会做的是:

cat a1Input.txt | ./interactive_script.sh

For example, imagine this simple script (copy-paste on terminal to create):例如,想象一下这个简单的脚本(在终端上复制粘贴来创建):

cat << EOF > questions.sh
#!/bin/bash
echo "What's your name ?"
read name
echo "What is your favourite movie ?"
read movie
echo "Hi \$name, i also love '\$movie' movie !!"
EOF

And these inputs:这些输入:

cat << EOF > inputs.txt
Edu
Interstellar
EOF

Then, just execute:然后,只需执行:

chmod a+x questions.sh
cat inputs.txt | ./questions.sh

If your script is more complicated, consider using "expect", although this is quite complex.如果您的脚本更复杂,请考虑使用“expect”,尽管这非常复杂。

BRs BR

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM