Last Updated: February 25, 2016
·
1.161K
· destructuring

Chef in bash

UPDATE: I am actually seriously using this idea, implemented in a project named poop: https://github.com/destructuring/poop (as in, people will poo-poo this idea, or in the end, it's all crap anyways).

Pretend I want these chef-like resources to execute in bash without ruby.

directory "$HOME/dir"
  owner "$USER"
  group "staff"
  mode 0755
end

link "dir"
  to "$HOME/slink"
end

Interesting, no? Wonder how far I could take this. Maybe check back to this protip and I'll have a git repo up =)

First, define the resource functions, directory and link.

function directory {
  resource="directory"
  name="$1"; shift
}

function link {
  resource="link"
  name="$1"; shift
}

Then define the attributes.

function owner {
  _owner="$1"; shift
}

function group {
  _group="$1"; shift
}

function mode {
  _mode="$1"; shift
}

function to {
  _to="$1"; shift
}

The end function does all of the work.

function end {
  case "$resource" in
    directory)
      mkdir -p "$name"
      [[ -n "$_owner" ]] && chown "$_owner" "$name"
      [[ -n "$_group" ]] && chgrp "$_group" "$name"
      [[ -n "$_mode" ]] && chmod "$_mode" "$name"
      ;;
    link)
      ln -nfs "$name" "$_to"
      [[ -n "$_mode" ]] && chmod "$_mode" "$_to"
      ;;
  esac

  unset _name _owner _group _mode _to
}