加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何一次定义类似的bash函数

发布时间:2020-12-16 01:44:28 所属栏目:安全 来源:网络整理
导读:我在?/ .bashrc中有这些函数: function guard() { if [ -e 'Gemfile' ]; then bundle exec guard "$@" else command guard "$@" fi}function rspec() { if [ -e 'Gemfile' ]; then bundle exec rspec "$@" else command rspec "$@" fi}function rake() { if
我在?/ .bashrc中有这些函数:

function guard() {
    if [ -e 'Gemfile' ]; then
    bundle exec guard "$@"
    else
    command guard "$@"
    fi
}
function rspec() {
    if [ -e 'Gemfile' ]; then
    bundle exec rspec "$@"
    else
    command rspec "$@"
    fi
}
function rake() {
    if [ -e 'Gemfile' ]; then
        bundle exec rake "$@"
    else
        command rake "$@"
    fi
}

如您所见,这些功能非常相似.我想一次定义这3个函数.有办法吗?

环境

bash --version
GNU bash,version 3.2.51(1)-release (x86_64-apple-darwin13)

解决方法

$cat t.sh
#!/bin/bash

for func in guard rspec rake; do
        eval "
        ${func}() {
                local foo=(command ${func})
                [ -e 'Gemfile' ] && foo=(bundle exec ${func})
                "${foo[@]}" "$@"
        }
        "
done

type guard rspec rake

.

$./t.sh
guard is a function
guard ()
{
    local foo=(command guard);
    [ -e 'Gemfile' ] && foo=(bundle exec guard);
    "${foo[@]}" "$@"
}
rspec is a function
rspec ()
{
    local foo=(command rspec);
    [ -e 'Gemfile' ] && foo=(bundle exec rspec);
    "${foo[@]}" "$@"
}
rake is a function
rake ()
{
    local foo=(command rake);
    [ -e 'Gemfile' ] && foo=(bundle exec rake);
    "${foo[@]}" "$@"
}

关于eval的常见警告适用.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读