Question about if else statements in bash

139 views Asked by At

I'm attempting to write a function for dwmbar in bash using playerctl to return metadata about a song.

If there is nothing playing, e.g. if playerctl status returns No players found. I want it to show nothing.

The example below however prints metadata at all times.

What have I done wrong?

[EDITED]

mpd() {
  PS=$(2>/dev/null playerctl status)

  echo "$(date): ${PS}" >> debug.log
 
  if ! [[ "${PS}" =~ ".*No play.*" ]];then  
      MD=$(2>/dev/null playerctl metadata --format '{{uc(artist) }}|{{uc(title)}}')
      TITLE=$(echo ${MD} | cut -d'|' -f 1)
      ARTIST=$(echo ${MD} | cut -d '|' -f 2)

      printf "^c$pink^ ^c$blue^${TITLE}"
      printf "^c$pink^${ARTIST}^c$blue^ "
    else    
      # Do you really need a space printed here?
      printf " "
      # Do you really need to exit from inside a function?
      exit 0 
    fi
}   

(Prior post)

mpd() {
  PS=$(2>/dev/null playerctl status)

  echo "$(date): ${PS}" >> debug.log

  if [[ ${PS} == "No players available" ]];then          
      printf "^c$pink^ ^c$blue^$(playerctl metadata --format '{{ uc(artist) }}') "
      printf "^c$pink^$(playerctl metadata --format '{{ uc(title) }}')^c$blue^ "
    else    
      # Do you really need a space printed here?
      printf " "
      # Do you really need to exit from inside a function?
      exit 0 
    fi
}   

Edit: this works

mpd() {
PS=$(2>/dev/null playerctl status)
NP='No players'

  if [[ "$PS" == *"$NP"* ]]; then
    printf " "
  else
    printf "^c$pink^ ^c$blue^$(playerctl metadata --format '{{ uc(artist) }}') "
    printf "^c$pink^$(playerctl metadata --format '{{ uc(title) }}')^c$blue^ "

  fi
} 
1

There are 1 answers

0
2346254765 On

This works:

mpd() {
PS=$(2>/dev/null playerctl status)
NP='No players'

  if [[ "$PS" == *"$NP"* ]]; then
    printf " "
  else
    printf "^c$pink^ ^c$blue^$(playerctl metadata --format '{{ uc(artist) }}') "
    printf "^c$pink^$(playerctl metadata --format '{{ uc(title) }}')^c$blue^ "

  fi
}