Skip to content

Instantly share code, notes, and snippets.

@sheldonhull
Created September 21, 2023 18:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sheldonhull/b30c52cb236965da8cc43ab48f4fecdb to your computer and use it in GitHub Desktop.
Save sheldonhull/b30c52cb236965da8cc43ab48f4fecdb to your computer and use it in GitHub Desktop.
dynamically creating shell command based on conditions

I'm having issues with a shell function that tries to change the command line args dynamically based on conditions.

In PowerShell this would be simple with: Invoke-Expression "& mods -s $(ModelString)" or several other ways. Another example:

$MyArgs = @(
  '-mods', 'claude'
 )
 $MyArgs += '--verbose'
 
 & $($MyArgs -join ' ')

In zsh/bash I'm not having much luck.

Setup:

remoteurl=$(git remote -v | awk '/origin.*fetch/ {print $2}' | grep -qE 'myinternalVCserver.com' && echo true || echo false)
modsmodifier=""


if [[ $remoteurl == true ]]; then
  # check for TACO_OPENAI_KEY since detecting an internal repo
  printf '\e[90m%s\e[0m\n' "using TACO_OPENAI_KEY due to target repo being internal"
  if [[ -z $TACO_OPENAI_KEY ]]; then
    printf '\e[33m%s\e[0m\n' '⬜ TACO_OPENAI_KEY not found. Add to .zshenv or .bashrc' &&
      return 1
  fi
  modsmodifier="--api taco"
else
  # a personal or github repo, so use personal openai key
  printf '\e[90m%s\e[0m\n' "using personal OPENAI_API_KEY"
  if [[ -z $OPENAI_API_KEY ]]; then
    printf '\e[33m%s\e[0m\n' '⬜ OPENAI_API_KEY not found. Add to .zshenv or .bashrc' &&
      return 1
  fi
  modsmodifier="--api openai"
fi

Condition should be dynamically switching the modsmodifer.

The current hard coded command:

msg="$(git diff --cached | mods --api taco --status-text "Writing commit message" $customprompt)" &&
  printf '\n' &&
  gum write --header=" Look good? Ctrl+D to commit." --value="$msg" &&
  git commit -am "$msg"

Now, when I try to use various string expansion approches, none of them have worked.

  • hard coded, works: msg="$(git diff --cached | mods --api taco --status-text "Writing commit message" $customprompt)"
  • msg="$(git diff --cached | mods ${modsmodifier} --status-text "Writing commit message" $customprompt)"
  • msg="$(git diff --cached | mods $modsmodifier --status-text "Writing commit message" $customprompt)"
  • msg=$(eval "$(git diff --cached | mods $( --status-text "Writing commit message" $customprompt)")

Not certain what the best way to dynamically build the final command is. I had also wanted to not wrap in a string and just make it dynamic on the pipeline directly but gave that up too.

Any tips? Make a mention of my name please so I am sure to see it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment