Bash Variables Use in Linux

Bash Variables

  • Variables are named values
    • useful for storing data or command output
  • Referenced with ${VARIABLE}

$ HI="Hello, and welcome to $(hostname) . "
$ echo ${HI}
Hello, and welcome to stationX.

Sometimes it is helpful to be able to store information and reference it later. In bash, this is done with variables. bash recognizes that you are trying to set a variable when it sees the pattern text=text. Note that there can be no spaces on either side of the = or you will get an error.

So, to set the variable FILES to the output of ls /etc. you would type
[user@stactionX ~]$ FILES=$(ls /etc/)

You can access the value of a variable by enclosing its name in ${ }. This is called dereferencing or expanding the variable.

[user@stationX ~] $ echo ${FILES}
a2ps.cfg a2ps-site.cfg acpi adjtime alchemist aliases aliases.db allegrorc alsa alternatives anacrontab ant.conf ant.d apt asound.state at.deny audit autofs_ldap_auth.conf auto.master auto.misc auto.smb avahi bashrc... output truncated ...

You will find variables very useful for writing more complex shell scripts and for configuring some programs, which look for the values of certain variables rather than reading a configuration file.

There is nother syntax available that does not use the { } characters. However, it is not recommended Consider these two commands:

[root@stationX ~]# cp -a /etc /mnt/backup/$HOSTNAME_$(date +%F)
[root@stationX ~]# cp -a /etc /mnt/backup/${HOSTNAME}_$(date +%F)

The first example will back up to /mnt/backup/_YYY-MM-DD, because there is no variable named “HOSTNAME_”. (Unless you have defined it beforehand. HOSTNAME is set by default.) The second will back up to /mnt/backup/stationX_YYY-MM-DD as intended.

Leave a Comment

%d bloggers like this: