Monday 17 January 2022

Linux Environment Variables

 

Working with Environment Variables

To list all environment variables and their values use:

$ env

To display the value of some particular env var use echo $ENV_VAR_NAME. Example:

$ echo $GOPATH
/home/test_user/dev/go

To set environment variables for the single command:

Example:

$ env GOOS=linux GOARCH=amd64 go build cmd/main.go

From the executable's point of view, the same would have been achieved without using env:

$ GOOS=linux GOARCH=amd64 go build cmd/main.go

To set environment variables for the current terminal session:

$ export GOPATH=/mnt/c/dev/go

export is a bash builtin. export key=value is extended syntax and should not be used in portable scripts (i.e. #! /bin/sh)

What's the difference between set, export and env and when should I use each?
What is the difference between set, env, declare and export when setting a variable in a Linux shell?

If some bash script calls executable which requires some env variables, we also need to use export.Example:

demo.sh:

#!/bin/bash
...
echo
echo Env variables:
go env
export CGO_ENABLED=0
export GOOS=linux
export GOARCH=amd64 
echo
echo Env variables:
go env
go build -o './bin/myapp' -v './cmd/main.go'

...gives the output:

Env variables:
[16:33:25][Step 4/7] GOARCH="amd64"
[16:33:25][Step 4/7] GOOS="linux"
[16:33:25][Step 4/7] CGO_ENABLED="1"
...
[16:33:25][Step 4/7] 
[16:33:25][Step 4/7] Env variables:
[16:33:25][Step 4/7] GOARCH="amd64"
[16:33:25][Step 4/7] GOOS="linux"
[16:33:25][Step 4/7] CGO_ENABLED="0"
...

How do I add environment variables?
How to set an environment variable only for the duration of the script?

To add en environment variable during the session of a particular user (and also make them available in terminal) append the desired var name and its value to ~/.profile file. Example:

export GOROOT=/usr/local/go
export GOPATH=$HOME/go
export PATH=$GOPATH/bin:$GOROOT/bin:$PATH

We'd need to restart the terminal in order to get these changes visible but to make terminal fetch them in the current session, we can update the current shell session with:

source ~/.profile

Alternatively we could have used a dot command:


. ~/.profile 



To add a new or modify existing environment variable permanently (to make environment variable persistent) (for non-root user) we need to change ~/.bashrc:

Example of ~/.bashrc snippet:

# ~/.bashrc: executed by bash(1) for non-login shells.
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples
...
export GOPATH=$HOME/dev/go
export PATH=$PATH:$GOPATH/bin


To do the same for root user, open /etc/environment:

$ sudo gedit /etc/environment

...and add desired path:

PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games"
GOPATH="/home/test_user/dev/go"

 

 

Linux Default Environment Variables


user@host:~/$ echo $HOSTNAME
host

 

 

No comments: