Reading Environment Variables
After defining variables, including as part of Workflow Configuration, you will want to read them back in your Workflow.
In Alfred objects, variable contents are expanded with the format {var:myvariable}
, where myvariable
is the name you gave your variable when creating it. In code blocks, such as in a Run Script or Script Filter, they are set as environment variables and you access them according to the rules of the language.
The following examples assign the contents of a myvariable
environment variable to a new thevalue
variable.
Zsh and Bash
thevalue="${myvariable}"
JavaScript (JXA)
ObjC.import("stdlib")
var thevalue = $.getenv("myvariable")
var thevalue = $.NSProcessInfo.processInfo.environment.objectForKey("myvariable").js
The top version will throw an error if the environment variable does not exist, while the bottom one will not.
AppleScript
set thevalue to (system attribute "myvariable")
use framework "Foundation"
set thevalue to (current application's NSProcessInfo's processInfo's environment's objectForKey:"myvariable") as text
The top version is shorter and easier to read, while the bottom one is necessary if you imported Foundation
for other parts of the script.
Swift
import Foundation
var thevalue: String? = ProcessInfo.processInfo.environment["myvariable"]
Python
import os
thevalue = os.environ["myvariable"]
import os
thevalue = os.getenv("myvariable")
The top version will throw an error if the environment variable does not exist, while the bottom one will not.
Ruby
thevalue = ENV['myvariable']
Perl
$thevalue = $ENV{myvariable};
PHP
$thevalue = getenv('myvariable');