你如何创建一个"功能工厂"在bash中,生成的函数接受自己的命令行参数?

时间:2018-01-27 17:37:18

标签: bash

我喜欢使用命令行工具howdoi。默认情况下,它会搜索stackoverflow.com,但我也想配置howdoi来搜索其他StackExchange网站。根据{{​​3}},编写bash函数以配置howdoi以搜索任意StackExchange站点非常容易:

function howdoi-serverfault { HOWDOI_URL=serverfault.com howdoi $@; }

但似乎这很难维护,因为你必须为你想访问的每个StackExchange站点编写一个函数。

我考虑将这种模式概括为一个"功能工厂",以便在我想搜索新网站时易于维护...

function howdoi-factory
{
  eval "
  function $1 {
      echo "Searching $2 for $@";
      HOWDOI_URL=$2 howdoi $@;
    }
  "
}

howdoi-factory howdoi-engineer softwareengineering.stackexchange.com

我希望代码能做什么:

> howdoi-engineer write good code
Searching softwareengineering.stackexchange.com for write good code
(answers relating to the keywords "write good code")

实际获得的内容:

> howdoi-engineer write good code
Searching softwareengineering.stackexchange.com for howdoi-engineer softwareengineering.stackexchange.com
(answers relating to the keywords "howdoi-engineer softwareengineering.stackexchange.com")

我需要做些什么才能确保我的函数工厂能够生成能够接受自己的命令行参数的函数,而不是重复使用"原始"命令行参数?

1 个答案:

答案 0 :(得分:3)

使用printf %q格式字符串安全地格式化数据以包含在函数中。

gen-howdoi() {
  local text
  for arg; do
    printf -v text 'howdoi-%q() { HOWDOI_URL=%q howdoi "$@"; }' "${arg%.*}" "$arg"
    eval "$text"
  done
}

# this creates howdoi-serverfault and howdoi-stackoverflow
gen-howdoi serverfault.com stackoverflow.com