【问题标题】:Reading in input from text file, Bash script从文本文件中读取输入,Bash 脚本
【发布时间】:2020-06-18 14:05:30
【问题描述】:

我是使用 Bash 编写脚本的新手,我正在做一个创建库存系统的任务。我已经编写了所有脚本,它们都使用标准输入终端工作。我现在希望从名为 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


我最初的 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


【问题讨论】:

  • ..... esac done <a1Input.txt ? bashfaq how to read a file line by line
  • 你什么时候收到q: Command not found.?您是否编辑了文件并尝试使用:!q 退出(应该是:q!)?还是脚本名为q 而你在命令行中给出了q(应该是./q)?

标签: bash text-files stdin


【解决方案1】:

我将文件中的输入注入交互式脚本的方法是:

cat a1Input.txt | ./interactive_script.sh

例如,想象一下这个简单的脚本(在终端上复制粘贴创建):

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

这些输入:

cat << EOF > inputs.txt
Edu
Interstellar
EOF

然后,执行:

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

如果您的脚本更复杂,请考虑使用“expect”,尽管这相当复杂。

BR

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-03
    • 2014-10-26
    • 1970-01-01
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多