How do I make an environment variable set in a StackScript available to a login shell?

Linode Staff

I setup a Linode using a simple StackScript which creates an environment variable using export envVar=value, but after logging in I run printenv envVar and it has no value. Shouldn't I be able to see that value after logging in as root?

2 Replies

Exporting an environment variable from a script will only make it available to the environment in which the script is running, but you can still achieve the desired result from a StackScript (or any other script). Instead of exporting the variable directly in the script, put the command into ~/.profile and the variable will become available to any shell to which that user logs in. You can do so with a script like this:

#!/bin/bash

echo `export envVar=value` >> ~/.profile

To be sure, I created a Linode running Debian 10 and can confirm that the variable was only available to other login shells when it was in ~/.profile.

@tommydavidson writes:

Instead of exporting the variable directly in the script, put the command into ~/.profile and the variable will become available to any shell to which that user logs in.

This is great if you only have one user with a .profile… Using your solution, the export will have to appear in the .profile for every user on the system with a login shell (that's what ~ means). The proper way to do this is to put the code into /etc/profile…the system-wide .profile file for the Bourne shell (sh(1) and Bourne-compatible shells…bash(1), ksh(1), ash(1), …). You have to have super-user privileges to modify /etc/profile.

There's are similar files for zsh(1) and csh(1) as well. I just don't remember what they are at the moment…

This single change affects every user that uses a Bourne-compatible shell as their login shell. With great power comes great responsibility…

-- sw

Reply

Please enter an answer
Tips:

You can mention users to notify them: @username

You can use Markdown to format your question. For more examples see the Markdown Cheatsheet.

> I’m a blockquote.

I’m a blockquote.

[I'm a link] (https://www.google.com)

I'm a link

**I am bold** I am bold

*I am italicized* I am italicized

Community Code of Conduct