Jump to content

How to use Bash variable in Script Filter output?


Recommended Posts

I’m trying to create a workflow that will display the current time when I type "time" into Alfred.

 

I can’t figure out how to use a bash variable within the JSON object in the heredoc. This is what I have but the item doesn’t show. If I add other fields the one with the variable remains empty.

 

time = date "+%H:%M %p"

cat << EOB
{"items": [

	{
		"title": $time
	}

]}
EOB

 

I’ve also tried "$time" and '$time' but nothing works. I feel like I’m missing something basic.

Link to comment

A user had a similar request a few months ago. See the post for some insights (there are screenshots showing the code).

Regarding your script, there are a few things wrong. To show a variable in bash, you may use either $var or ${var} (I recommend the latter). To run a command, you use either `command` or $(command) (again, I recommend the latter).

 

In bash, you cannot have spaces between the variable name and it’s contents. So var = contents does not work; you need var=contents. Also, you should always quote the contents. But in this case, time='date "+%H:%M %p"' wouldn’t even work, as it would save that text, which is not what you want. You need time=$(date "+%H:%M %p") so the date command is executed and the result included in time.

 

The Bash Academy is a somewhat recent website that aims to help you get to grips with bash. You may wish to check it.

Link to comment

Thanks to both of you! With your help I got it working.

 

I better bone up on bash some more…

 

Here’s the final Script Filter in case others looking for the same thing happen upon this thread:

 

time=$(date "+%I:%M %p")
date=$(date "+%A, %B %d, %Y")

cat << EOB
{"items": [

	{
		"uid": "time",
		"title": "${time}",
		"subtitle": "${date}"
	}

]}
EOB

 

Edited by clearphase
Corrected JSON as per deanishe’s reply.
Link to comment
3 minutes ago, clearphase said:

Thanks to both of you! With your help I got it working.

 

I better bone up on bash some more…

 

Here’s the final Script Filter in case others looking for the same thing happen upon this thread:

 


time=$(date "+%I:%M %p")
date=$(date "+%A, %B %d, %Y")

cat << EOB
{"items": [

	{
		"uid": "time",
		"title": "${time}",
		"subtitle": "${date}",
	}

]}
EOB

 

 

That JSON is actually invalid. You need to remove the trailing comma here: "subtitle": "${date}",

 

That is to say, it should read "subtitle": "${date}"

 

Edited by deanishe
Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...