It can be useful to set temporary environment variables from the command line in Linux. Even more useful is the output of a long command being set to a single environment variable. Below I show an example of setting an environment variable followed by setting an environment variable to the output of a command or string of commands.
Set Environment Variable In Linux:
- root@ubuntu-dev:~# VARIABLE1=1234567890
- root@ubuntu-dev:~# export VARIABLE1
- root@ubuntu-dev:~# echo $VARIABLE1
- 1234567890
- root@ubuntu-dev:~#
Easy enough. So now if you wanted to set an environment variable to the output of a command or string of commands you might expect that you could set VARIABLE2=thecommand but if there are spaces, slashes, ticks, etc. it will break the output. Instead you have to issue the command similar to VARIABLE2=(the command) as shown in the below example.
werwerwer
Set Environment Variable From Command Output In Linux:
- root@ubuntu-dev:~# VARIABLE2=$(/sbin/ifconfig eth1 | grep 'inet addr:' | cut -d: -f2| cut -d' ' -f1)
- root@ubuntu-dev:~# export VARIABLE2
- root@ubuntu-dev:~# echo $VARIABLE2
- 192.168.1.1
- root@ubuntu-dev:~#
As you can see the output of the command is now set to the variable.