Most “it works in my terminal but not in the script” problems come down to one thing: the environment. A variable you thought was set isn’t, a variable that’s set doesn’t reach the program that needs it, or the file you edited isn’t the one Bash reads.
This post covers all three, with real output from Ubuntu 26.04 and RHEL 9: the variables every script leans on, the difference between a local and an exported variable, and exactly which startup file Bash reads when several exist. If you haven’t met login and interactive shells yet, our first Bash script guide explains them; we build on that here.
Bash environment variables explained: PATH, HOME, USER and SHELL
Here are the four big ones on our Ubuntu box:
echo $HOME $USER $SHELL
/home/asif asif /bin/bash
echo $PATH | tr : "\n"
/home/asif/.local/bin
/usr/local/bin
/usr/bin
/bin
/usr/local/games
/usr/games
/snap/bin
PATH: where commands come from
When you type a command, the shell checks each directory in PATH from left to right and runs the first match. type -a shows every match, in order:
type -a python3 ls
python3 is /usr/bin/python3
python3 is /bin/python3
ls is /usr/bin/ls
ls is /bin/ls
Order matters. Put a directory earlier and its programs win, which is how ~/.local/bin lets you override system tools, and also how a bad PATH can run the wrong program. The same user on RHEL 9 gets a different PATH (it adds ~/bin and the sbin directories but no games or snaps), so never assume a PATH in a script. Use full paths for anything important.
HOME and USER: and what sudo does to them
HOME is your home directory (what ~ expands to) and USER is your login name. Simple, until sudo gets involved:
sudo env | grep -E "^(USER|HOME|SHELL|LOGNAME)="
HOME=/root
LOGNAME=root
SHELL=/bin/bash
USER=root
Under sudo, a script that writes to $HOME/backups writes to /root/backups, not yours. Usually what you want, occasionally a nasty surprise. If you need the original user, sudo sets $SUDO_USER.
SHELL: your login shell, not your current one
This one confuses people constantly:
zsh -c 'echo "running zsh, but SHELL=$SHELL"'
running zsh, but SHELL=/bin/bash
SHELL holds your default login shell from /etc/passwd. It doesn’t change when you start another shell. To see what’s actually running, use echo $0 or ps -p $$.
How PWD, OLDPWD, HOSTNAME, LANG and TERM affect shell scripts
PWD and OLDPWD
PWD is your current directory and OLDPWD the previous one. cd - uses it to jump back:
asif@mylinux:~$ cd /var/log
asif@mylinux:/var/log$ cd /etc
asif@mylinux:/etc$ echo "PWD=$PWD OLDPWD=$OLDPWD"
PWD=/etc OLDPWD=/var/log
asif@mylinux:/etc$ cd -
/var/log
Two things matter for scripts. First, a script runs in its own process, so a cd inside it never changes the directory of the shell that ran it. Second, PWD keeps symlinks in the path, while pwd -P shows the real location:
asif@mylinux:~$ ln -sfn /var/log ~/logs; cd ~/logs
asif@mylinux:~/logs$ pwd; pwd -P
/home/asif/logs
/var/log
If a script compares paths or calculates relative locations, use the physical path (pwd -P or realpath) or you’ll get mismatches that only show up on servers with symlinked directories.
HOSTNAME: set on one distro, empty on the other
Here’s a difference that breaks #!/bin/sh scripts moving between Ubuntu and RHEL. On Ubuntu:
printenv HOSTNAME; echo "shell var: $HOSTNAME"
shell var: mylinux
bash -c 'echo child sees HOSTNAME=[$HOSTNAME]'; sh -c 'echo sh sees HOSTNAME=[$HOSTNAME]'
child sees HOSTNAME=[mylinux]
sh sees HOSTNAME=[]
printenv prints nothing, because HOSTNAME isn’t an environment variable on Ubuntu. Bash invents it for itself, so Bash children have it, but sh (dash) gets an empty string. Same test on RHEL 9:
printenv HOSTNAME; echo "shell var: $HOSTNAME"
app1
shell var: app1
bash -c 'echo child sees HOSTNAME=[$HOSTNAME]'; sh -c 'echo sh sees HOSTNAME=[$HOSTNAME]'
child sees HOSTNAME=[app1]
sh sees HOSTNAME=[app1]
RHEL’s /etc/profile sets and exports it explicitly:
45:HOSTNAME=$(/usr/bin/hostnamectl --transient 2>/dev/null) || \
46:HOSTNAME=$(/usr/bin/hostname 2>/dev/null) || \
47:HOSTNAME=$(/usr/bin/uname -n)
The portable fix is to not rely on the variable at all: host=$(hostname) works everywhere.
LANG: the same sort, a different answer
LANG (and the LC_* variables) controls locale: language, character set, and also how text is sorted and compared. Same file, sorted twice:
echo "LANG=$LANG"
LANG=en_US.UTF-8
sort ~/words.txt
Apple
banana
cherry
_tmp
Zebra
LC_ALL=C sort ~/words.txt
Apple
Zebra
_tmp
banana
cherry
In en_US.UTF-8 sorting ignores case and mostly ignores punctuation. In the C locale it’s plain byte order: uppercase first, then _, then lowercase. A script that sorts, compares sorted output, or uses uniq and comm can give different results on two servers with different locales. Set export LC_ALL=C at the top of scripts that need predictable byte-order results (and it’s faster too).
TERM: why tput and clear fail in automation
TERM tells programs what kind of terminal they’re drawing on. In an SSH session it’s xterm or similar. But run a command over SSH without a terminal, the way automation does:
ssh asif@mylinux 'echo "TERM=[${TERM-unset}]"; tput cols; clear; echo "exit=$?"'
TERM=[dumb]
exit=1
tput: No value for $TERM and no -T specified
TERM environment variable not set.
There’s a twist here. With no terminal, Bash sets TERM=dumb for itself, as an unexported shell variable. So echo $TERM says “dumb”, but child programs like tput and clear see no TERM at all and fail. Under cron it’s simply unset:
cat /tmp/cronterm.txt # written by cron
TERM=[unset] LANG=[en_US.UTF-8]
tput: No value for $TERM and no -T specified
If a script uses colors or tput, guard it with [ -t 1 ] (is stdout a terminal?) or set TERM=xterm explicitly for that command, so the same script works interactively and from cron.
Local variables vs exported variables in Bash
This is the rule behind most of the surprises above: a plain variable belongs to the current shell only. export marks it to be copied into the environment of every program the shell starts.
app_env=staging
echo "in this shell: app_env=$app_env"
bash -c 'echo "in a child: app_env=[$app_env]"'
export app_env
bash -c 'echo "after export: app_env=[$app_env]"'
declare -p app_env
in this shell: app_env=staging
in a child: app_env=[]
after export: app_env=[staging]
declare -x app_env="staging"
Before export, the child sees nothing. After it, the child gets a copy. declare -p shows the -x flag that marks a variable as exported. And it really is a copy, which only flows one way:
child changed it to: production
parent still has: staging
A child process can never change its parent’s variables. That’s why a script that sets variables can’t set them in your terminal, unless you source it so it runs in your current shell.
Three more forms worth knowing:
# set a variable for one command only
one-off for one command: DB_HOST=10.0.0.5
afterwards in the parent: DB_HOST=[]
# export -n removes the export flag again
after export -n: app_env=[]
# env -i starts a program with an empty environment
env -i: PATH=[/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin] HOME=[] USER=[]
The first came from DB_HOST=10.0.0.5 bash -c '...': putting the assignment in front of a command exports it to that one command and nowhere else. Perfect for one-off overrides. env -i is a great debugging tool: run your script with env -i bash script.sh and you’ll find every place it quietly depended on your personal environment. (That PATH is Bash’s built-in fallback.)
The counts tell the story too. In one session there were 45 shell variables (set) but only 16 in the environment (env). Most of what your shell knows never reaches your programs.
.bashrc vs .bash_profile vs .profile: which file does Bash read?
When Bash starts as a login shell, it looks in your home directory for three files, in order, and reads only the first one it finds:
~/.bash_profile~/.bash_login~/.profile
~/.bashrc isn’t on that list at all. Bash reads it for interactive non-login shells, and login shells only get it if one of the files above sources it. To prove the order, I created a test user with a marker line in all four files and logged in over SSH, deleting files between logins:
##### 1) all four files exist
>> ~/.bash_profile
PATH has .local/bin? no
##### 2) after deleting ~/.bash_profile
>> ~/.bash_login
##### 3) after deleting ~/.bash_login too
>> ~/.profile
>> ~/.bashrc
PATH has .local/bin? yes
Look at case 1. With a ~/.bash_profile present, Bash ignored ~/.profile entirely, and with it Ubuntu’s ~/.local/bin PATH addition and the line that loads ~/.bashrc. That’s the classic “I created .bash_profile and my aliases and PATH vanished” bug. If you create a ~/.bash_profile, make it source the others:
# ~/.bash_profile
[ -f ~/.profile ] && . ~/.profile
[ -f ~/.bashrc ] && . ~/.bashrc
Ubuntu ships only ~/.profile (which sources ~/.bashrc). RHEL ships ~/.bash_profile (which also sources ~/.bashrc). Both work; just don’t add the other one on top without thinking.
Other shells care too. ~/.profile is the only one that non-Bash shells read. Here’s dash started as a login shell:
##### 4) dash as a login shell: sh -l
>> ~/.profile
dash done
dash read ~/.profile and skipped ~/.bashrc, because Ubuntu’s .profile only loads .bashrc when $BASH_VERSION is set. That’s why ~/.profile is the portable home for environment variables.
The system-wide files
Before your own files, Bash reads system-wide ones, and their names differ by distro:
# Ubuntu 26.04
/etc/bash.bashrc
/etc/environment
/etc/profile
/etc/profile.d
# RHEL 9
/etc/bashrc
/etc/environment
/etc/profile
/etc/profile.d
/etc/profile runs for login shells and then everything in /etc/profile.d/*.sh. That folder is the right place for site-wide settings you add yourself, as a new file, because package updates leave your files there alone. For interactive shells, Ubuntu’s Bash reads /etc/bash.bashrc itself, while on RHEL your ~/.bashrc sources /etc/bashrc, so deleting that line from ~/.bashrc drops the system defaults. /etc/environment isn’t a script at all; it’s plain KEY=value lines read by PAM at login, and on Ubuntu it’s where the default system PATH lives:
PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin"
So where should each setting go?
- Environment variables (
PATHadditions,EDITOR,JAVA_HOME):~/.profile, or~/.bash_profileif that’s what your distro uses. Set once per login, inherited by everything. - Aliases, functions, prompt, shell options:
~/.bashrc, below the “not interactive, return” check. They aren’t inherited anyway, so they need to load in every interactive shell. - For all users: a new file in
/etc/profile.d/. - For scripts and cron: none of the above. Set what the script needs inside the script, or at the top of the crontab. Our cron jobs guide covers that side.
After editing, either log out and back in, or load the change into your current shell with source ~/.bashrc (or source ~/.profile).
Frequently asked questions
What’s the difference between env, printenv, set and declare?
env and printenv list exported environment variables, the ones child programs receive. set lists everything the shell knows, including unexported variables and functions. declare -p NAME shows one variable with its attributes, such as -x for exported.
How do I make a PATH change permanent?
Add a line like export PATH="$HOME/tools/bin:$PATH" to ~/.profile (Ubuntu and Debian) or ~/.bash_profile (RHEL family), then log in again. Put the new directory first if it should win over system commands, or last if it should only fill gaps.
Why doesn’t my alias work inside a script?
Aliases live in ~/.bashrc, scripts run in a non-interactive shell that doesn’t read it, and Bash doesn’t expand aliases in scripts by default anyway. Use a function or the full command in scripts.
Can a script change my current shell’s variables or directory?
Not when you run it normally, because it runs as a child process and children can’t change their parent. Run it with source script.sh (or . script.sh) to execute it in your current shell instead.
Is it safe to put secrets in environment variables?
Convenient, but limited. Exported variables are visible to every child process and, on Linux, to anyone who can read that process’s /proc/PID/environ, which is the same user and root. Fine for a lab; for production, prefer a secrets manager or a file readable only by the service account.