Jocomol
Jocomol

Reputation: 322

exporting env variables in linux doesn't work with variables

I am trying to export the value of $fullPath to an env variable with the key WALLPAPER_PATH. But when I execute the following script, the var is empty

/home/joco/.wallpapers/setwallpaper

#!/bin/bash
wallpapers=/home/joco/.wallpapers/pictures/
folder=$(ls $wallpapers | shuf -n1)
file=$(ls $wallpapers$folder | shuf -n1)
fullPath=file://$wallpapers$folder/$file
gsettings set org.gnome.desktop.background picture-uri $fullPath
export WALLPAPER_PATH=$fullPath

Shell

╭─joco@Nantaror ~/.wallpapers ‹master*› 
╰─$ ./setwallpaper

╭─joco@Nantaror ~/.wallpapers ‹master*› 
╰─$ echo $WALLPAPER_PATH

╭─joco@Nantaror ~/.wallpapers ‹master*› 
╰─$

as you can see it's empty.

Upvotes: 1

Views: 890

Answers (1)

John1024
John1024

Reputation: 113814

Don't execute the script. Source it, like . ~/.wallpapers/setwallpaper.

When a shell script is executed, it is run as a child process and children can never affect the environment of their parents.

In bash, as an alternative to the dot-notation above, it is possible to source a script with a source command, like source ~/.wallpapers/setwallpaper. This form, however, is non-standard (non-POSIX) and will not work under some very common shells like dash (which is the default /bin/sh on debian and ubuntu-like systems).

Additional note: Unless you explicitly want word-splitting and pathname expansion, shell variables should always be inside double-quotes.

Upvotes: 2

Related Questions