Question

So, I'm trying to build a very small shell script that grabs the currently playing Spotify song and returns the lyrics of the song in the terminal.

What works

The applescript returns/echos the track name to the terminal

What I need help with

I can't seem to retrieve values of theArtist and theName from the applescript, to use in the curl command below.

Any tips on how to make this work? :)

echo "tell application \"Spotify\"
        set theTrack to current track
        set theArtist to artist of theTrack
        set theName to name of theTrack
    end tell" | osascript

song=`curl -s "http://makeitpersonal.co/lyrics?artist=$theArtist&title=$theName"`

echo -e "$theArtist - $theName\n$song"
Was it helpful?

Solution

Try:

# Get information from Spotify via AppleScript and store it in shell variables:
IFS='|' read -r theArtist theName <<<"$(osascript <<<'tell application "Spotify"
        set theTrack to current track
        set theArtist to artist of theTrack
        set theName to name of theTrack
        return theArtist & "|" & theName
    end tell')"

# Create *encoded* versions of the artist and track name for inclusion in a URL:
theArtistEnc=$(perl -MURI::Escape -ne 'print uri_escape($_)' <<<"$theArtist")
theNameEnc=$(perl -MURI::Escape -ne 'print uri_escape($_)' <<<"$theName")

# Retrieve lyrics via `curl`:
lyrics=$(curl -s "http://makeitpersonal.co/lyrics?artist=$theArtistEnc&title=$theNameEnc")

# Output combined result:
echo -e "$theArtist - $theName\n$lyrics"
  • AppleScript implicitly returns the result of the last statement; thus, in order to return multiple items of information, build up a string to return with an explicit return statement .
  • You then need to parse the output string into its components using read (here I've chosen | as a separator, because it's unlikely to be contained in artist names or song titles) and assign them to shell variables (AppleScript is an entirely separate world, and its variables are not accessible to the shell - the information must be passed via output string).
  • For the curl command to work, the information you splice into the URL must be properly URL-encoded (e.g., Pink Floyd must be encoded as Pink%20Floyd), which is what the perl commands do.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top