Skip to content
ImagineWorld

Understanding Variables and Pipelines

node_idnode-book_the-ultimate-linux-shell-scripting-guide_chapter-03-understanding-variables-and-pipelines
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num3
chapter_titleUnderstanding Variables and Pipelines
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 3 — Understanding Variables and Pipelines

Section titled “Chapter 3 — Understanding Variables and Pipelines”

In the previous chapter, you saw how the shell interprets users’ commands, and you saw various examples of how to craft your commands. In this chapter, I’ll tell you about variables and pipelines.

The ability to create variables and assign values to them is an important part of any programming environment. As you would expect, both bash and zsh have this capability. In the first part of this chapter, we’ll cover the basics about environmental variables and programming variables.

In the second part of the chapter, we’ll cover how to use pipelines. Pipelines are very simple, and you might have already used them at some point. So, I promise to make this write-up both short and sweet. (Actually, there’s not a lot to say just yet about either of these topics, which is why I’m combining both of them into one chapter.)

Topics in the chapter include:

  • Understanding environmental variables
  • Understanding programming variables
  • Understanding pipelines

If you’re ready, let’s get started.

Understanding Environmental Variables

Environmental variables control the configuration and functioning of the operating system shell. When you install either a Linux or Unix/Unix-like operating system such as FreeBSD or OpenIndiana, you’ll find that a default set of environmental variables has already been defined at both the global and user levels.

To see the list of environmental variables and their settings, use the env command, like so:

Terminal window
[donnie@fedora ~]$ env
SHELL=/bin/bash
IMSETTINGS_INTEGRATE_DESKTOP=yes
COLORTERM=truecolor
XDG_CONFIG_DIRS=/etc/xdg/lxsession:/etc/xdg
HISTCONTROL=ignoredups
...
...
MAIL=/var/spool/mail/donnie
OLDPWD=/etc/profile.d
_= /bin/env
[donnie@fedora ~]$

The complete list of environmental variables is very extensive. Fortunately, you don’t need to memorize what each and every item does for you. Most of the ones that you do need to know are self-explanatory.

Instead of viewing the entire list, you can also view the value of a specific item. Just use the echo command, and precede the variable name with a $, like so:

Terminal window
[donnie@fedora ~]$ echo $USER
donnie
[donnie@fedora ~]$ echo $PATH
/home/donnie/.local/bin:/home/donnie/bin:/home/donnie/.cargo/bin:/usr/local/
bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin
[donnie@fedora ~]$ echo $EDITOR
/usr/bin/nano
[donnie@fedora ~]$

Here we see that I (donnie) am the current logged-in user, what my path setting is, and what my default editor is. You would view the value of any other environmental variable the same way.

An important thing to note is that the names of all environmental variables always consist of all upper-case letters. Nothing in either the operating system or the shell prevents the use of lower-case letters, but there is a very good reason for not using them. It’s just that variable names are case-sensitive. Best practice dictates using nothing but upper-case letters for environmental variable names and either all lower-case letters or a mix of upper and lower-case letters for programming variable names. This will prevent you from accidentally overwriting the value of an environmental variable. (I’ll show you more about that in the next section.)

As I mentioned before, environmental variables are configured at both the global and user levels. Variable settings at the global level affect all users of bash and zsh. For bash, you’ll find most of these global settings in the /etc/profile file, the /etc/bashrc file, and various files in the /etc/profile.d/ directory. For zsh, you’ll find these settings in the /etc/zprofile, /etc/zshrc, and /etc/zshenv files. (Note that zsh also references the same /etc/profile file that bash references.) If you were to open one of these files at this point, you likely won’t understand much of what’s going on in them. That’s okay, because for now that doesn’t matter. But, you’ll easily be able to find where the environmental variables are set, because the variable names are all in upper-case letters.

Now, let’s say you don’t like a particular setting. For example, let’s say that you want to customize your command-line prompt to your own liking. Here on my Fedora workstation, my bash prompt looks like this:

The format of the prompt is determined by the PS1 environmental variable. We can see the PS1 settings like this:

Terminal window
[donnie@fedora ~]$ echo $PS1
[\u@\h \W]$
[donnie@fedora ~]$

Here’s the breakdown of what you’ve just seen:

  • [: This is a literal character, which is the first thing we see in the prompt.
  • \u: This causes the current user’s username to appear.
  • @: This is another literal character.
  • \h: This causes the first component of the machine’s hostname to appear.
  • \W: This causes the name of the current working directory to appear. Note that the upper-case W doesn’t cause the entire pathname to appear.
  • ]: This is another literal character.
  • $: This causes the $ to show for all normal users, and the # to appear for the root user.

A while ago, I said that we can use the \ to force the shell to interpret a metacharacter as a literal character. Here though, we see another use for the . When configuring the PS1 parameters, the \ indicates that we’re about to use a macro command. (Think of a macro as a command that runs when you perform some simple action, such as hitting a specific key or clicking on a specific button.)

Now, let’s say that we want the entire path of the current working directory to appear, along with the current date and time. To do that, we’ll replace the \W with \w, and add the \d and \t macros, like this:

Terminal window
[donnie@fedora ~]$ export PS1="[\d \t \u@\h \w]$
[Wed Aug 09 18:14:26 donnie@fedora ~]$

Note that I had to surround the new parameter within a pair of quotes so that the shell would interpret the metacharacters properly. Also, note what happens when I cd into a down-level directory:

[Wed Aug 09 18:14:26 donnie@fedora ~]$cd /etc/profile.d/
[Wed Aug 09 18:29:15 donnie@fedora /etc/profile.d]$

Substituting the /w for the /W causes the entire path of the current working directory to show up.

When you configure the PS1 parameter from the command-line, the new settings will disappear as soon as you either log out from the machine or close the terminal window. To make the setting permanent, just edit the .bashrc file that’s in your home directory. Add the export PS1=”[\d \t \u@\h \w]$” line to the end of the file, and you’ll see the new prompt the next time you either log into the machine or open a new terminal window.

There are still a lot more ways to customize the command prompt that I haven’t shown you. For a more complete list, see the reference that I provided in the Further Reading section. Also, note that I’ve only covered how to do this with bash, because zsh uses different command prompt parameters. (I’ll show you all about that in Chapter 22, Using the Z Shell.)

I can read your mind, and can see that you’re wondering what environmental variables have to do with shell scripting. Well, it’s just that sometimes you’ll need to have your script perform a specific action that depends upon the value of a specific environmental variable. For example, let’s say that you only want the script to run for the root user, and not for any unprivileged user. Since we know that the user identification number for the root user is Θ, we can write code that allows the script to run if the UID variable is set to Θ, and to prevent the script from running if the UID is set to anything other than Θ.

And by the way, I apologize if it seems a bit creepy that I can read your mind.

That does it for our introduction to environmental variables. Let’s now take a quick look at programming variables.

Understanding Programming Variables

Sometimes, it’s necessary to define variables to use in your scripts. You can define, view, and unset these variables as needed for your programming needs. Note that although the system will allow you to create programming variable names with all upper-case letters, it’s considered bad form to do so. Best practice is to always name your programming variables with lower-case letters, so that you won’t risk accidentally overwriting the value of an environmental variable with the same name. (Of course, you won’t cause any long-term damage by overwriting an environmental variable. But, why risk overwriting an environmental variable that you might need to use later in your script?)

To show how this all works, let’s create some programming variables from the command-line, and view the assigned values. First, we’ll create the car variable and assign to it the value Ford, like this:

Terminal window
[donnie@fedora ~]$ car=Ford
[donnie@fedora ~]$ echo $car
Ford
[donnie@fedora ~]$

To view the value of a variable, use echo, and precede the name of the variable with a $, just as we did with the environmental variables. Now, let’s open a child shell with the bash command, to see if we can still view the value of this car variable, and then exit back to the parent shell, like this:

Terminal window
[donnie@fedora ~]$ bash
[donnie@fedora ~]$ echo $car
[donnie@fedora ~]$ exit
<!-- page: 063 (printed 49) -->
exit
[donnie@fedora ~]$

We can’t see the value of car this time, because we didn’t export the variable. Exporting the variable will permit a child shell to access the variable. As you might have guessed, we’ll use the export command to do this, like so:

Terminal window
[donnie@fedora ~]$ export car=Ford
[donnie@fedora ~]$ echo $car
Ford
[donnie@fedora ~]$ bash
[donnie@fedora ~]$ echo $car
Ford
[donnie@fedora ~]$ exit
exit
[donnie@fedora ~]$

This time, we see that the value of car now shows up in the child shell.

We’ll be working with variables throughout the rest of this book, so you’ll be learning a lot more about how to use them. For now though, this quick introduction is enough.

Next, let’s do some plumbing.

Understanding Pipelines

A pipe will take the output of one command and use it as the input for another command. It’s represented by the | symbol, which is on the same key as the backslash. You’ll often invoke a simple pipeline from the command-line for various purposes. But, you can also create very complex, multi-stage pipelines for your shell scripts.

[!visual-conversion] Figure 3.1: Creating a pipeline. Note that stdout is short for Standard Output, and stdin is short for Standard Input. Page scans unavailable; diagram reconstructed as ASCII from the in-text description.

+-----------+ stdout +--------+ stdin +-----------+
| command 1 | ----------> | pipe | ----------> | command 2 |
| (ls -l) | | | | | (less) |
+-----------+ +--------+ +-----------+

To see how this can be useful, let’s say that you want to look at a listing of all files in a certain directory. But, there are so many files that the output would scroll off of the screen where you’d never be able to see it. You can solve the problem by taking the output of the ls command and using it as the input for the less command. It would look something like this:

Terminal window
[donnie@fedora ~]$ ls -l | less

The ls -l listing will open in the less pager, so that you can scroll through the output or perform searches for particular text strings.

Now, let’s say that I only want to see files with the text string alma in their filenames. That’s easy enough. I’ll just pipe the ls -l output into grep, like so:

Terminal window
[donnie@fedora ~]$ ls -l | grep alma
-rw-r--r--. 1 donnie donnie 1438 Nov 2 2022 alma9_default.txt
-rw-r--r--. 1 donnie donnie 1297 Nov 2 2022 alma9_future.txt
-rw-r--r--. 1 donnie donnie 81 Jan 11 2023 alma_link.txt
[donnie@fedora ~]$

Now, let’s say that I don’t want to see the filenames, but I do want to know how many files there are. I’ll just add another pipe stage, like so:

Terminal window
[donnie@fedora ~]$ ls -l | grep alma | wc -l
3
[donnie@fedora ~]$

The wc -l command counts the number of lines in the output, which in this case tells us how many files I have that contain the text string alma in their filenames.

If you’re not familiar with grep, just understand for now that it’s a utility that can search for either specific text strings or for text patterns. It can search through text files without you having to open them, or it can search for text strings or patterns in the output that you would pipe into it from another command.

Okay, I’ve shown you some simple examples of how to create pipelines from the command-line. Now, I want to show you something that I hope you’ll never do. This involves using the cat utility.

One thing that you can do with cat is to dump the contents of a text file to your screen. It’s mainly useful for viewing small files, as you see here:

Terminal window
[donnie@fedora ~]$ cat somefile.txt
This is just some file that I created to demonstrate cat.
[donnie@fedora ~]$

If you use cat to view a large file, the output will scroll off of the screen where you might not be able to view it. I have seen cases where somebody would still use cat to dump the file, and then pipe the output into less, like so:

Terminal window
[donnie@fedora ~]$ cat files.txt | less

I’ve also seen people pipe cat output into grep to search for a text string, like this:

Terminal window
[donnie@fedora ~]$ cat files.txt | grep darkfi
drwxr-xr-x. 1 donnie donnie 414 Apr 3 12:41 darkfi
[donnie@fedora ~]$

Both of these examples work, but it requires less typing to just use either less or grep without cat, like so:

Terminal window
[donnie@fedora ~]$ less files.txt
· · ·
· · ·
[donnie@fedora ~]$ grep darkf1 files.txt
drwxr-xr-x. 1 donnie donnie 414 Apr 3 12:41 darkf1
[donnie@fedora ~]$

In other words, although piping cat output into other utilities does work, it’s less efficient than just directly using the other utilities, and can make your scripts a bit less efficient and a bit harder to read. And, as a real-life lover of cats, it always bothers me to see someone engaging in cat abuse.

What I’ve shown you here is just scratching the surface of what you can do with pipelines. A major reason why Linux and Unix administrators need to create shell scripts is to automate the extraction and formatting of information from either text files or the output of certain programs. Doing that often requires very long, complex, multi-stage pipelines with a different extraction or formatting utility at each stage. Before you can start doing that, you’ll need to learn how to use these utilities, which you’ll begin doing in Chapter 6, Text Stream Filters – Part 1. And, before we can get to that, we need to cover a few more basic functions of bash and zsh.

Summary

Although this chapter has been rather short, we covered a good bit of important information. We began by looking at environmental variables, showing how to modify one of them, and explaining why you might need to use environmental variables in your shell scripts. Next, we covered programming variables, explaining how to create and export them. Finally, we did a bit of plumbing work by creating some pipelines.

In the next chapter, we’ll cover the concept of input/output redirection. I’ll see you there.

Questions

  1. Which of the following metacharacters allows you to view the assigned value of a variable? a. * b. % c. $ d. ^

  2. Which of the following statements is true? a. It’s perfectly correct to use either all upper-case or all lower-case letters to create your programming variable names. b. Variable names are not case-sensitive.

c. You should always use upper-case letters to create the names of programming variables. d. You should always use lower-case letters to create the names of programming variables.

  1. How would you cause a child shell to recognize a variable that you created in the parent shell? a. In the child shell, import the variable from the parent shell. b. In the parent shell, use the export keyword when creating the variable. c. You can’t, because the parent shell and child shell are isolated from each other. d. The child shell and the parent shell always share variables by default.

  2. Which of these metacharacters would you use to take the output of one command and use it at the input of another command? a. $ b. | c. & d. %

-further Reading

Answers

  1. c
  2. d
  3. b
  4. b

Join the CloudPro Newsletter with 44000+ Subscribers Want to know what’s happening in cloud computing, DevOps, IT administration, networking, and more? Scan the QR code to subscribe to CloudPro, our weekly newsletter for 44,000+ tech professionals who want to stay informed and ahead of the curve.

https://packt.link/cloudpro