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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL linux(("`Linux`")) -.-> linux/BasicSystemCommandsGroup(["`Basic System Commands`"]) linux(("`Linux`")) -.-> linux/InputandOutputRedirectionGroup(["`Input and Output Redirection`"]) linux(("`Linux`")) -.-> linux/TextProcessingGroup(["`Text Processing`"]) linux(("`Linux`")) -.-> linux/UserandGroupManagementGroup(["`User and Group Management`"]) linux(("`Linux`")) -.-> linux/FileandDirectoryManagementGroup(["`File and Directory Management`"]) linux(("`Linux`")) -.-> linux/BasicFileOperationsGroup(["`Basic File Operations`"]) linux(("`Linux`")) -.-> linux/VersionControlandTextEditorsGroup(["`Version Control and Text Editors`"]) shell(("`Shell`")) -.-> shell/BasicSyntaxandStructureGroup(["`Basic Syntax and Structure`"]) shell(("`Shell`")) -.-> shell/VariableHandlingGroup(["`Variable Handling`"]) shell(("`Shell`")) -.-> shell/ControlFlowGroup(["`Control Flow`"]) shell(("`Shell`")) -.-> shell/FunctionsandScopeGroup(["`Functions and Scope`"]) shell(("`Shell`")) -.-> shell/AdvancedScriptingConceptsGroup(["`Advanced Scripting Concepts`"]) shell(("`Shell`")) -.-> shell/SystemInteractionandConfigurationGroup(["`System Interaction and Configuration`"]) linux/BasicSystemCommandsGroup -.-> linux/declare("`Variable Declaring`") linux/BasicSystemCommandsGroup -.-> linux/source("`Script Executing`") linux/BasicSystemCommandsGroup -.-> linux/exit("`Shell Exiting`") linux/BasicSystemCommandsGroup -.-> linux/echo("`Text Display`") linux/InputandOutputRedirectionGroup -.-> linux/pipeline("`Data Piping`") linux/InputandOutputRedirectionGroup -.-> linux/redirect("`I/O Redirecting`") linux/BasicSystemCommandsGroup -.-> linux/man("`Manual Access`") linux/BasicSystemCommandsGroup -.-> linux/printf("`Text Formatting`") linux/TextProcessingGroup -.-> linux/sort("`Text Sorting`") linux/UserandGroupManagementGroup -.-> linux/env("`Environment Managing`") linux/FileandDirectoryManagementGroup -.-> linux/cd("`Directory Changing`") linux/FileandDirectoryManagementGroup -.-> linux/mkdir("`Directory Creating`") linux/FileandDirectoryManagementGroup -.-> linux/find("`File Searching`") linux/FileandDirectoryManagementGroup -.-> linux/which("`Command Locating`") linux/FileandDirectoryManagementGroup -.-> linux/whereis("`File/Command Finding`") linux/BasicFileOperationsGroup -.-> linux/ls("`Content Listing`") linux/BasicFileOperationsGroup -.-> linux/mv("`File Moving/Renaming`") linux/UserandGroupManagementGroup -.-> linux/sudo("`Privilege Granting`") linux/BasicFileOperationsGroup -.-> linux/chmod("`Permission Modifying`") linux/VersionControlandTextEditorsGroup -.-> linux/gedit("`Graphical Text Editing`") linux/UserandGroupManagementGroup -.-> linux/set("`Shell Setting`") linux/UserandGroupManagementGroup -.-> linux/export("`Variable Exporting`") linux/UserandGroupManagementGroup -.-> linux/unset("`Variable Unsetting`") linux/VersionControlandTextEditorsGroup -.-> linux/vimdiff("`File Difference Viewing`") shell/BasicSyntaxandStructureGroup -.-> shell/shebang("`Shebang`") shell/BasicSyntaxandStructureGroup -.-> shell/comments("`Comments`") shell/BasicSyntaxandStructureGroup -.-> shell/quoting("`Quoting Mechanisms`") shell/VariableHandlingGroup -.-> shell/variables_decl("`Variable Declaration`") shell/VariableHandlingGroup -.-> shell/variables_usage("`Variable Usage`") shell/VariableHandlingGroup -.-> shell/str_manipulation("`String Manipulation`") shell/VariableHandlingGroup -.-> shell/param_expansion("`Parameter Expansion`") shell/ControlFlowGroup -.-> shell/for_loops("`For Loops`") shell/ControlFlowGroup -.-> shell/exit_status("`Exit and Return Status`") shell/FunctionsandScopeGroup -.-> shell/scope_vars("`Scope of Variables`") shell/AdvancedScriptingConceptsGroup -.-> shell/arith_expansion("`Arithmetic Expansion`") shell/AdvancedScriptingConceptsGroup -.-> shell/subshells("`Subshells and Command Groups`") shell/AdvancedScriptingConceptsGroup -.-> shell/adv_redirection("`Advanced Redirection`") shell/SystemInteractionandConfigurationGroup -.-> shell/shell_options("`Shell Options and Attributes`") subgraph Lab Skills linux/declare -.-> lab-17996{{"`Environment Variable and Find Files`"}} linux/source -.-> lab-17996{{"`Environment Variable and Find Files`"}} linux/exit -.-> lab-17996{{"`Environment Variable and Find Files`"}} linux/echo -.-> lab-17996{{"`Environment Variable and Find Files`"}} linux/pipeline -.-> lab-17996{{"`Environment Variable and Find Files`"}} linux/redirect -.-> lab-17996{{"`Environment Variable and Find Files`"}} linux/man -.-> lab-17996{{"`Environment Variable and Find Files`"}} linux/printf -.-> lab-17996{{"`Environment Variable and Find Files`"}} linux/sort -.-> lab-17996{{"`Environment Variable and Find Files`"}} linux/env -.-> lab-17996{{"`Environment Variable and Find Files`"}} linux/cd -.-> lab-17996{{"`Environment Variable and Find Files`"}} linux/mkdir -.-> lab-17996{{"`Environment Variable and Find Files`"}} linux/find -.-> lab-17996{{"`Environment Variable and Find Files`"}} linux/which -.-> lab-17996{{"`Environment Variable and Find Files`"}} linux/whereis -.-> lab-17996{{"`Environment Variable and Find Files`"}} linux/ls -.-> lab-17996{{"`Environment Variable and Find Files`"}} linux/mv -.-> lab-17996{{"`Environment Variable and Find Files`"}} linux/sudo -.-> lab-17996{{"`Environment Variable and Find Files`"}} linux/chmod -.-> lab-17996{{"`Environment Variable and Find Files`"}} linux/gedit -.-> lab-17996{{"`Environment Variable and Find Files`"}} linux/set -.-> lab-17996{{"`Environment Variable and Find Files`"}} linux/export -.-> lab-17996{{"`Environment Variable and Find Files`"}} linux/unset -.-> lab-17996{{"`Environment Variable and Find Files`"}} linux/vimdiff -.-> lab-17996{{"`Environment Variable and Find Files`"}} shell/shebang -.-> lab-17996{{"`Environment Variable and Find Files`"}} shell/comments -.-> lab-17996{{"`Environment Variable and Find Files`"}} shell/quoting -.-> lab-17996{{"`Environment Variable and Find Files`"}} shell/variables_decl -.-> lab-17996{{"`Environment Variable and Find Files`"}} shell/variables_usage -.-> lab-17996{{"`Environment Variable and Find Files`"}} shell/str_manipulation -.-> lab-17996{{"`Environment Variable and Find Files`"}} shell/param_expansion -.-> lab-17996{{"`Environment Variable and Find Files`"}} shell/for_loops -.-> lab-17996{{"`Environment Variable and Find Files`"}} shell/exit_status -.-> lab-17996{{"`Environment Variable and Find Files`"}} shell/scope_vars -.-> lab-17996{{"`Environment Variable and Find Files`"}} shell/arith_expansion -.-> lab-17996{{"`Environment Variable and Find Files`"}} shell/subshells -.-> lab-17996{{"`Environment Variable and Find Files`"}} shell/adv_redirection -.-> lab-17996{{"`Environment Variable and Find Files`"}} shell/shell_options -.-> lab-17996{{"`Environment Variable and Find Files`"}} end

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