10

How could I read an environmental variable that a user has set?

I'm new to desktop development on the Mac (cocoa), and I am building a little tool that I can use to access amazon's s3 service.

I set my environmental variables in my .bash_profile, but I want this to work regardless of where the user entered it (.bashrc, .bash_profile or .profile etc).

mmmmmm
  • 32,227
  • 27
  • 88
  • 117
loyalflow
  • 14,275
  • 27
  • 107
  • 168
  • 3
    If you set an environment variable in `.bash_profile`, `.bashrc`, etc. it won't be accessible from GUI app. Those files store environment variables for the CLI only, you should store the environment variables elsewhere if you want them to be readable by GUI applications. See http://stackoverflow.com/questions/135688/setting-environment-variables-in-os-x It might be easier just to ask the user to enter the information again, and store it in the Keychain or in preferences as appropriate. – Dietrich Epp Jul 18 '12 at 21:13

2 Answers2

19

Look at the environment method on a NSProcessInfo. It returns a NSDictionary of the environment so e.g. for PATH

NSString* path = [[[NSProcessInfo processInfo]environment]objectForKey:@"PATH"];
mmmmmm
  • 32,227
  • 27
  • 88
  • 117
5

You can use a C API from the GNU library http://www.gnu.org/software/libc/manual/html_node/Environment-Access.html#Environment-Access

converting to NSString: modern obj-c:

NSString *envVarString = @(getenv("__MY_ENV_NAME__"));

legacy obj-c:

NSString *envVarString = [NSString stringWithUTF8String: getenv("__MY_ENV_NAME__")];
Patrick
  • 537
  • 4
  • 17