首页 > 解决方案 > 如何使用循环变量响应 shell 脚本中的提示

问题描述

我有一个 cli 命令来删除像 admin delete <<entity>>.

现在,我的用例是删除文件中具有实体名称的一堆实体。我可以遍历文件并删除这些实体,例如:

cat file.txt | while read entity 
do
   admin delete $entity
done 

问题是该admin delete <<entity>>命令在删除实体之前要求确认实体名称,例如To proceed, type the full name of the entity again here.

如何在每个实体的 shell 脚本执行期间输入循环变量作为对此提示的响应?

标签: linuxbashshell

解决方案


一个简单的解决方法是使用here document.

admin delete $entity <<< $entity

比较:

fn() { local x && read x; [ "$x" = "$1" ] && echo yep || echo nope; }

运行为

var=smthg
foo=smthg
fn $var <<< $foo

推荐阅读