Environment Variable and Find Files

ShellShellBeginner
Practice Now

Introduction

This section introduces the role and the usage of environment variables, as well as several ways to search for documents. After learning these techniques, you're one step closer to becoming a Linux master.

Variable

A variable is a symbolic representation within a computer that stores a value, which can be numeric, character or string data. Variables are used in various operations, allowing values to be read from and assigned to other variables, as well as specifying values to be assigned to any variable. Similar to variables in programming languages, shell variables share the concept of different types and scopes, and can participate in operations and processing.

How to create a variable in the shell and read the value of that variable? Let's take a look at the following example:

Use the command declare to create a variable named tmp:

declare tmp

You don't need to declare a variable first, and you can create it when you want to use it later.

Use = to assign the variable tmp to labex

tmp=labex

Use echo and $ to read the value of a variable๏ผˆ$ is used to refer to the value of a variable, don't forget to enter it.๏ผ‰:

echo $tmp
labex:project/ $ declare tmp
labex:project/ $ tmp=labex
labex:project/ $ echo $tmp
labex

It is not the case that any random form of variable names is permitted. Variable names can only contain letters, digits, and underscores. In addition, names starting with a digit are not allowed.

Environment Variables

The scope of an environment variable is more significant than a custom variable. For example, a shell's environment variable can affect this very shell and its child processes. Every process has its own environment variable settings in all UNIX and UNIX-like systems.

We will use three variable types:

  • Private custom variables of the current shell process, such as tmp we've created above, which is only valid in the current shell;
  • Built-in variable of shell;
  • Environment variables derived from custom variables.

There are three commands related to the above three environment variables set, env, and export. These three commands are very similar, and all are used to print environment variable information. The range of variables involved varies, though.

Command Description
set It can display all the variables of the current shell, including its built-in environment variables, user-defined variables, and exported environment variables.
env It can display the environment variables associated with the current user and allow the command to run in the specified environment.
export It displays variables exported from the shell as environment variables and can also export custom variables as environment variables.
temp=labex
export temp_env=labex
env | sort > env.txt
export | sort > export.txt
set | sort > set.txt

In the above commands, the command output is sorted using the command sort and finally redirected the result to the object file.

You can use vimdiff to compare the differences between them:

vimdiff env.txt export.txt set.txt

The variable valid for the child process of the current process is the environment variable, and others are not environment variables. We use export to check the validity of variables in sub-shells. First, we set a variable temp = labex in the shell. And then, we create a sub-shell to see the variable temp value.

To distinguish between environment variables and ordinary variables, we often name the environment variables with uppercase letters.

How to Make Environment Variables Permanent

Environment variables are gone when you shut down or close the current shell. So how can we make environment variables permanent?

According to the variable life cycle, Linux variables can be divided into two categories:

  1. Permanent Variables: You need to modify a configuration file. Then the variables will be effective permanently;

  2. Temporary Variables: Use only the export command at the shell prompt. The variables get invalid when the shell is closed.

Linux has two critical files, /etc/bashrc and /etc/profile. They store shell variables and environment variables. Note that there is a hidden file in every user directory, .profile. You can use ls -a to view this file:

cd /home/labex
ls -a

.profile is valid only for the current user. However, environment variables written in the /etc/profile are valid for all users. So if you want to add a valid environment variable, open the /etc/profile and add the environment variable at the end of the file.

Find the Path and Order for a Command

When we enter a command in the shell, how does the shell know where to find this command? This is done by the environment variable PATH. PATH saves the search paths of commands.

View the contents of the PATH environment variable

echo $PATH

By default, you will see the following output.

/opt/swift/usr/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/home/labex/anaconda3/bin

Next, we will practice creating the most straightforward executable shell script and a hello world program using C language. If you have not learned that, then you need to complete an introductory course first:
Linux Shell Scripting Tutorial (LSST) v2.0.

Create a directory named mybin in the ~/project directory. And go to this directory:

cd ~/project
mkdir mybin
cd mybin

Then, create a Shell script file:

gedit hello_shell.sh

Add the following in the script, then save and exit๏ผˆDo not omit the first line.๏ผ‰:

#! /bin/bash

for ((i = 0; i < 10; i++)); do
  echo "hello shell"
done

exit 0

Add the executable permission to this script file:

chmod 755 hello_shell.sh

Run the script:

./hello_shell.sh

Then we go back to the ~/project directory. When you want to run the programs using the above commands, the terminal will display: "Command cannot be found." This is because you need to add the full path to the programs, which is very inconvenient. How to do the same as using system commands to execute our programs? How to run our programs from outside their directories? We can add the paths to their directories to the PATH environment variable.

To Modify and Delete Existing Variables

Variable Modification

Variables can be modified in the following ways:

Setting method Description
${name#match string} From front to back, delete the shortest string that matches the string
${name##match string} From front to back, delete the longest string that matches the string
${name%match string} From back to front, delete the shortest string that matches the string
${name%%match string} From back to front, delete the longest string that matches the string
${nameold stringnew string} Replace the first string that matches the old string with the new string
${nameold stringnew string} Replace all strings that match the old string with the new string

To Delete an Environment Variable

You can use unset to delete an environment variable:

unset temp

View the result:

labex:project/ $ echo $temp
labex
labex:project/ $ unset temp
labex:project/ $ echo $temp

labex:project/ $

How to Make the Environment Variables Take Effect Immediately

When we modify the configuration script, we must re-open the terminal or restart the host before it takes effect. It is very troublesome, but we can use the source command to let it work immediately, such as:

source ~/.zshrc

. is an alias for source. So you can use it like this:

. /home/labex/.zshrc

When you use ., the following file must specify the full absolute or relative path name, but source is not required.

  • whereis
whereis who

View the result:

labex:mybin/ $ whereis who
who: /usr/bin/who /usr/share/man/man1/who.1.gz

You use this command to find three paths. Two are the paths of executable files, and the third is the path of a man online help file. This search is rapid because it does not look up from the hard disk; instead, it queries directly from the database. whereis can only search for binary files (-b), man help files (-m), and source code files (-s).

  • which

which is a built-in shell command. We usually use which to determine whether to install a software package because it only searches from the PATH environment variable to search for a command. For example, to search for man, run this command:

which man
  • find

Find should be the most powerful of these commands. It can not only find files by file type or name but also search for files based on file attributes (such as file timestamp, file permissions, etc.).
The following command can search for a file or directory named interfaces in the /etc directory. This is the most common form of find. Remember the first parameter of find is the search destination:

sudo find /etc -name interfaces

Time-related parameters:

Parameter Description
-atime Last visit time (Last access time)
-ctime The last time when the contents of the file were modified
-mtime The last time when the file attributes were modified

Take -mtime for example:

  • -mtime n: The file that was modified on the day n days ago
  • -mtime +n: List the files that were modified n days ago (not including the nth day)
  • -mtime -n: List the files that have been modified within n days (including the day)
  • -newer file: List all the files that are more recent than the existing file named file

List all the files that have changed within 24 hours:

find ~ -mtime 0

List all the files that are more recent than the project folder in the user directory:

find ~ -newer /home/labex/project

Summary

In this lab, you learned how to use the find command to find files and directories. You also learned how to use the export command to set environment variables.

Other Shell Tutorials you may like