Jacob Jackson
Jacob Jackson

Reputation: 364

How to Run a Shell Command in a zsh-theme?

So, I have Oh My Zsh up and running, and I'm creating my own new zsh-theme. In it, I wish to grab the external IP address from https://api.myip.com - and I'm using curl & grep to grab it. Works fine when I enter it at the command prompt, but when embedded in my zsh-theme file it gives me an error:

zsh: no matches found: ((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5]).){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])
(23) Failed writing body

Jacobs-MacBook-Pro-2.local jacobjackson ttys002 0 [                               ] 10/29/20 18:32:46 PM

Here is my zsh-theme:

PROMPT='%F{white}%M %n %y %j $(curl -s https://api.myip.com | grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])') %F{green}%2c%F{blue} [%f '
RPROMPT='$(git_prompt_info) %F{blue}] %F{green}%W %* %F{yellow}%D{%p}%f'

ZSH_THEME_GIT_PROMPT_PREFIX="%F{yellow}"
ZSH_THEME_GIT_PROMPT_SUFFIX="%f"
ZSH_THEME_GIT_PROMPT_DIRTY=" %F{red}*%f"
ZSH_THEME_GIT_PROMPT_CLEAN=""

And here is the command sequence that grabs the IP address:

curl -s https://api.myip.com | grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])'

Upvotes: 1

Views: 613

Answers (2)

Marlon Richert
Marlon Richert

Reputation: 6985

Try this:

# Function name that's compatible with
# http://zsh.sourceforge.net/Doc/Release/User-Contributions.html#Prompt-Themes
# in case you ever want to build a full prompt theme.
# -s to prevent curl from outputting a progress bar.
# Use a service that simply outputs your IP, so you 
# don't have to parse anything.
prompt_jacobjackson_precmd() { 
  psvar[1]=$( curl -s ifconfig.co )
}

# precmd hooks ru  just before each new prompt.
autoload -Uz add-zsh-hook 
add-zsh-hook precmd prompt_jacobjackson_precmd

# %1v inserts the 1st element of the psvar array. See
# http://zsh.sourceforge.net/Doc/Release/Prompt-Expansion.html#Conditional-Substrings-in-Prompts
PS1='%1v > '

Upvotes: 2

Jacob Jackson
Jacob Jackson

Reputation: 364

I decided to use some of Marlon Richert's ideas as well a few from the zsh-theme 'bureau.' :)

get_space () {
  local STR=$1$2
  local zero='%([BSUbfksu]|([FB]|){*})'
  local LENGTH=${#${(S%%)STR//$~zero/}}
  local SPACES=""
  (( LENGTH = ${COLUMNS} - $LENGTH - 1))

  for i in {0..$LENGTH}
    do
      SPACES="$SPACES "
    done

  echo $SPACES
}

_1LEFT="%F{white}$(curl -s https://api.myip.com | jq .ip -r) %F{green}\$(dirs -c; dirs)"
_1RIGHT="%F{yellow}%j jobs %F{cyan}\$(~/systemstatus.sh)"

actionjackson_precmd () {
  _1SPACES=`get_space $_1LEFT $_1RIGHT`
  #print
  print -rP "$_1LEFT$_1SPACES$_1RIGHT"
}

setopt prompt_subst
PROMPT='%F{yellow}%n%F{white}@%F{green}%M $_LIBERTY%f '
RPROMPT='$(actionjackson_git_prompt)  %F{green}%W %* %F{yellow}%D{%p}%f'

autoload -U add-zsh-hook
add-zsh-hook precmd actionjackson_precmd

Upvotes: 0

Related Questions