我正在写一个剧本.Eg:
echo "my name is 'read' and am from 'read' city" > outfile.txt
当它运行时,它不会首先打印句子,即my name is
。相反,它要求首先为2个读取命令输入2个输入,然后形成完整的句子,如“我的名字是sudhir,我来自vizag city”
我希望脚本执行第一个“我的名字是read(ask for input)
并且来自read(ask for another input)
city”并且在输入后它应该一次性重定向到outfile.txt。
怎么办呢?用单句实现是否可行?
因为我想在一个文件中使用相同的480个问题的逻辑,而人们如何没有任何脚本知识应该能够在参考同一文件中存在的先前问题时添加更多问题。
没有一种漂亮的方法可以做到这一点,因为read
将换行字符从输入写入终端,但我们可以通过两次传递来完成。
您可以将以下内容放在脚本中
#!/bin/bash
echo -n 'my name is '; read -r name
echo -n ' and I am from '; read -r city
echo ' city'
printf "my name is %s and I am from %s city\n" \
"$name" "$city" > output.txt
对于用户来说,它看起来像这样
my name is sudhir
and I am from vizag
city
但它在文件中会是这样的
my name is sudhir and I am from vizag city
您可以编写一个带有占位符字符串的函数,并要求用户为每个字符串输入:
#!/bin/bash
fill() {
arg="$*"
result=""
while [[ "$arg" =~ ([^_]*)(_+)(.*) ]]
do
read -rp "${BASH_REMATCH[1]# }${BASH_REMATCH[2]}: " input
result+="${BASH_REMATCH[1]}${input}"
arg="${BASH_REMATCH[3]}"
done
result+="$arg"
printf '%s\n' "$result"
}
exec > outputfile
fill "My name is ____ and I am from ___."
fill "My new years resolution is ____."
例:
$ ./myscript
My name is ____: Sudhir
and I am from ___: Vizag
My new years resolution is ____: learning Bash instead of asking SO to write my scripts
$ cat outputfile
My name is Sudhir and I am from Vizag.
My new years resolution is learning Bash instead of asking SO to write my scripts.