shell - 数据驱动的 shell 编程?请提出建议

标签 shell data-driven

我想将我的 shell 脚本转换为使用数据驱动的方法。但是由于在任何 shell 中都没有“表”类型的值(据我所知),有什么建议的替代方法可以做到这一点?

我正在寻找的解决方案可以让人们做如下事情:

animals = [['horse', 300 'brown'],
           ['cat', 3, 'black'],
           ['elephant', 3000, 'grey'],
           ['mouse', 0.3, 'grey']]
for a in animals ; do
  echo "A typical $a[1] is $a[3] and weighs about $a[2] kilograms."
done

更准确地说,我想尝试一些命令,看看其中一个是否可用,然后向它发送参数:

commands = [['c1', '-m', '-i'],
            ['c2', '-message', '-icon'],
            ['c3', '/m', '/i']]
for c in commands ; do
  if exists c[1] ; then
    command = c[1]
    message_option = c[2]
    icon_option = c[3]
    break;
  fi
done
$command $message_option "message" $icon_option icon

最佳答案

不需要任何 bashism。这可以通过 while read 循环读取的 here-document 巧妙地解决:

#!/bin/sh
while read animal weigth colour; do
  printf '%s\n' "A typical $animal is $colour and weighs about $weight kilos."
done << EOF
horse 300 brown
cat 3 black
elephant 3000 grey
mouse 0.3 grey
EOF

观察这是如何按名称引用元素的,而不是使用 1、2、3 的神秘索引。它不会 fork /执行任何外部命令,并且击败了另一个答案中看到的循环体中的 3 个 awks。

关于shell - 数据驱动的 shell 编程?请提出建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40783097/

相关文章:

database - 使数据库ID一致和 "readable"的利弊

bash - -bash : mongo: command not found AWS

regex - Shell 脚本 - sed 不起作用

linux - 为什么这个简单的 FOR 循环在我的 Linux bash 中不起作用?

git - 显示 git 分支名称或提交 ID

java - 干净地实现数据驱动的 Swing 组件

linux - 需要在 bash 中的两个给定时间之间生成时间值

.net - 数据驱动的状态机应用

event-driven - 数据驱动与事件驱动模型/架构?

javascript - 将任意 Vue.js 组件添加到父组件