Chapter 5. Create, View, and Edit Text Files PDF
Document Details
Uploaded by DelectableLearning8178
Tags
Summary
This document explains how to redirect output and errors to files using shell redirection, including examples of common commands. It also explains the concepts of standard input, output, and error.
Full Transcript
Chapter 5. Create, View, and Edit Text Files Redirect Output to a File or Program Objectives Save output or errors to a file with shell redirection, and process command output through multiple command-line programs with pipes. Standard Input, Standard Output, and Standard Error...
Chapter 5. Create, View, and Edit Text Files Redirect Output to a File or Program Objectives Save output or errors to a file with shell redirection, and process command output through multiple command-line programs with pipes. Standard Input, Standard Output, and Standard Error A running program, or process, reads input and writes output. When you run a command from the shell prompt, it normally reads its input from the keyboard and sends its output to the terminal window. A process uses numbered channels called file descriptors to get input and send output. All processes start with at least three file descriptors. Standard input (channel 0) reads input from the keyboard. Standard output (channel 1) sends normal output to the terminal. Standard error (channel 2) sends error messages to the terminal. If a program opens separate connections to other files, then it might use higher- numbered file descriptors. Figure 5.1: Process I/O channels (file descriptors) The next table summarizes the information about the file descriptors: Table 5.1. Channels (File Descriptors) Number Channel name Description Default connection Usage 0 stdin Standard input Keyboard Read only 1 stdout Standard output Terminal Write only 2 stderr Standard error Terminal Write only 3+ filename Other files None Read, write, or both Redirect Output to a File The Input/Output (I/O) redirection changes how the process gets its input or output. Instead of getting input from the keyboard, or sending output and errors to the terminal, the process can read from or write to files. With redirection, you can save the messages to a file instead of displaying the output on the terminal. Alternatively, you can use redirection to discard output or errors, so they are not displayed on the terminal or saved. You can redirect a process stdout to suppress the process output from appearing on the terminal. If you redirect stdout to a file and the file does not exist, then the file is created. If the file does exist and the redirection does not append to the file, then the redirection overwrites the file's contents. To discard the output of a process, you can redirect to the empty /dev/null special file that discards channel output that is redirected to it. As viewed in the following table, redirecting only stdout does not suppress displaying stderr error messages on the terminal. Table 5.2. Output Redirection Operators Usag e Explanation Visual aid > file Redirect stdo ut to overwrite a file. Usag e Explanation Visual aid >> fil Redirect stdo e ut to append to a file. Usag e Explanation Visual aid 2> fil Redirect stde e rr to overwrite a file. Usag e Explanation Visual aid 2> Discard stder /dev/ r error null messages by redirecting them to /dev/null. Usag e Explanation Visual aid > file Redirect stdo 2>&1 ut and stderr &> fil to overwrite e the same file. Usag e Explanation Visual aid >> fil Redirect stdo e 2> ut and stderr &1 &>> f to append to ile the same file. Usag e Explanation Visual aid IMPORTANT The order of redirection operations is important. The following sequence redirects standard output to the output.log file and then redirects standard error messages to the same place as standard output (output.log). > output.log 2>&1 The next sequence redirects in the opposite order. This sequence redirects standard error messages to the default place for standard output (the terminal window, so no change) and then redirects only standard output to the output.log file. 2>&1 > output.log For this reason, some people prefer to use the merging redirection operators: &> output.log instead of > output.log 2>&1 &>> output.log instead of >> output.log 2>&1 (in Bash 4 or RHEL 6 and later) However, system administrators and programmers prefer to avoid the newer merging redirection operators when using alternative shells to bash (known as Bourne-compatible shells) for scripting commands. These new redirection operators are not standardized or implemented in those shells, and have other limitations. Examples for Output Redirection Simplify many routine administration tasks by using redirection. Use the previous table to assist, and consider the following examples: Save a time stamp in the /tmp/saved-timestamp file for later reference. [user@host ~]$ date > /tmp/saved-timestamp Copy the last 100 lines from the /var/log/secure file to the /tmp/last-100-log- secure file. [user@host ~]$ tail -n 100 /var/log/secure > /tmp/last-100-log-secure Concatenate all four step files into one file in the tmp directory. [user@host ~]$ cat step1.sh step2.log step3 step4 > /tmp/all-four-steps-in-one List the home directory's hidden and regular file names, and save the output to the my-file-names file. [user@host ~]$ ls -a > my-file-names Append a line to the existing /tmp/many-lines-of-information file. [user@host ~]$ echo "new line of information" >> /tmp/many-lines-of-information The next few commands generate error messages because some system directories are inaccessible to normal users. Observe the error message redirection. Redirect errors from the find command to the /tmp/errors file when viewing normal command output on the terminal. [user@host ~]$ find /etc -name passwd 2> /tmp/errors Save process output to the /tmp/output file and error messages to the /tmp/errors file. [user@host ~]$ find /etc -name passwd > /tmp/output 2> /tmp/errors Save process output to the /tmp/output file and discard error messages. [user@host ~]$ find /etc -name passwd > /tmp/output 2> /dev/null Store output and generated errors together to the /tmp/all-message-output file. [user@host ~]$ find /etc -name passwd &> /tmp/all-message-output Append output and generated errors to the /tmp/all-message-output file. [user@host ~]$ find /etc -name passwd >> /tmp/all-message-output 2>&1 Construct Pipelines A pipeline is a sequence of one or more commands that are separated by the vertical bar character (|). A pipeline connects the standard output of the first command to the standard input of the next command. Figure 5.8: Process I/O piping Use pipelines to manipulate and format the output of a process by other processes before it is output to the terminal. Imagine that data "flows" through the pipeline from one process to another, and is altered by each command in the pipeline that it flows through. NOTE Pipelines and I/O redirection both manipulate standard output and standard input. Pipelines send the standard output from one process to the standard input of another process. Redirection sends standard output to files, or gets standard input from files. Pipeline Examples The following list shows some pipeline examples: Redirect the output of the ls command to the less command to display it on the terminal one screen at a time. [user@host ~]$ ls -l /usr/bin | less Redirect the output of the ls command to the wc -l command, which counts the number of received lines from ls and prints that value to the terminal. [user@host ~]$ ls | wc -l Redirect the output of the ls -t command to the head command to display the first 10 lines, with the final result redirected to the /tmp/first-ten-changed-files file. [user@host ~]$ ls -t | head -n 10 > /tmp/first-ten-changed-files Pipelines, Redirection, and Appending to a File When you combine redirection with a pipeline, the shell sets up the entire pipeline first, and then it redirects the input/output. If you use output redirection in the middle of a pipeline, then the output goes to the file and not to the next command in the pipeline. In the next example, the output of the ls command goes to the /tmp/saved- output file, and the less command displays nothing on the terminal. [user@host ~]$ ls > /tmp/saved-output | less The tee command overcomes this limitation. In a pipeline, tee copies its standard input to its standard output and also redirects its standard output to the files that are given as arguments to the command. If you imagine data as water that flows through a pipeline, then you can visualize tee as a "T" joint in the pipe that directs output in two directions. Figure 5.9: Process I/O piping with tee Pipeline Examples with the tee Command The next example redirects the output of the ls command to the /tmp/saved- output file and passes it to the less command, so it is displayed on the terminal one screen at a time. [user@host ~]$ ls -l | tee /tmp/saved-output | less If you use the tee command at the end of a pipeline, then the terminal shows the output of the commands in the pipeline and saves it to a file at the same time. [user@host ~]$ ls -t | head -n 10 | tee /tmp/ten-last-changed-files Use the tee command -a option to append the content to a file instead of overwriting it. [user@host ~]$ ls -l | tee -a /tmp/append-files IMPORTANT You can redirect standard error through a pipeline, but you cannot use the merging redirection operators (&> and &>>). The following example is the correct way to redirect both standard output and standard error through a pipeline: [user@host ~]$ find / -name passwd 2>&1 | less Edit Text Files from the Shell Prompt Objectives Create and edit text files from the command line with the vim editor. Edit Files with Vim The fundamental design principle of Linux is that it supports storage of the information and configuration settings in text-based files. These files follow various structures such as lists of settings, INI-like formats, structured XML or YAML, and others. The advantage of storing files in a text-based structure is that they are edited with any text editor. Vim is an improved version of the vi editor, which is distributed with Linux and UNIX systems. Vim is a highly configurable and efficient editor that provides split- screen editing, color formatting, and highlighting for editing text. Benefits of the Vim Editor When a system uses a text-only shell prompt, you should know how to use at least one text editor for editing files. You can then edit text-based configuration files from a terminal window or remote logins through the ssh command or the Web Console. You also do not need access to a graphical desktop to edit files on a server, and that server might not need to run a graphical desktop environment. The key reason to learn Vim is that it is almost always installed by default on a server for editing text-based files. The Portable Operating System Interface or POSIX standard specified the vi editor on Linux, and many other UNIX- like operating systems largely do likewise. Vim is also used often as the vi implementation on other standard operating systems or distributions. For example, macOS currently includes a lightweight installation of Vim by default. So, Vim skills that are learned for Linux might also prove useful elsewhere. Get Started with Vim You can install the Vim editor in Red Hat Enterprise Linux by using either of two packages. These two packages provide different features and Vim commands for editing text-based files. With the vim-minimal package, you might install the vi editor with core features. This lightweight installation includes only the core features and the basic vi command. You can open a file for editing by using the vi command: [user@host ~]$ vi filename Alternatively, you can use the vim-enhanced package to install the Vim editor. This package provides a more comprehensive set of features, an online help system, and a tutorial program. Use the vim command to start Vim in this enhanced mode: [user@host ~]$ vim filename The core features of the Vim editor are available in both commands. If vim-enhanced is installed, then a shell alias is set so that if regular users run the vi command, then they automatically get the vim command instead. This alias does not apply to the root user and to other users with UIDs below 200 (which system services use). If vim-enhanced is installed and a regular user wants to use the vi command, then they might have to use the \vi command to override the alias temporarily. You can use \vi --version and vim --version to compare the feature sets of the two commands. Vim Operating Modes The Vim editor offers various modes of operation such as command mode, extended command mode, edit mode, and visual mode. As a Vim user, always verify the current mode, because the effect of keystrokes varies between modes. Figure 5.10: Moving between Vim modes When you first open Vim, it starts in command mode, which is used for navigation, cut and paste, and other text modification. Pressing the required keystroke accesses specific editing functions. An i keystroke enters insert mode, where all typed text becomes file content. Pressing Esc returns to command mode. A v keystroke enters visual mode, where multiple characters might be selected for text manipulation. Use Shift+V for multiline and Ctrl+V for block selection. To exit the visual mode, use the v, Shift+V, or Ctrl+V keystrokes. The : keystroke begins extended command mode for tasks such as writing the file (to save it) and quitting the Vim editor. NOTE If you are unsure which mode Vim is using, then press Esc a few times to get back into command mode. It is safe to press the Esc key in command mode repeatedly. The Minimum, Basic Vim Workflow Vim has efficient, coordinated keystrokes for advanced editing tasks. Although considered beneficial with practice, the capabilities of Vim can overwhelm new users. Red Hat recommends that you learn the following Vim keys and commands: The u key undoes the most recent edit. The x key deletes a single character. The :w command writes (saves) the file and remains in command mode for more editing. The :wq command writes (saves) the file and quits Vim. The :q! command quits Vim, and discards all file changes since the last write. Learning these commands helps a Vim user to accomplish any editing task. Rearrange Existing Text In Vim, you can yank and put (copy and paste), by using the y and p command characters. Position the cursor on the first character to select, and then enter visual mode. Use the arrow keys to expand the visual selection. When ready, press y to yank the selection into memory. Position the cursor at the new location, and then press p to put the selection at the cursor. Visual Mode in Vim Visual mode is useful to highlight and manipulate text in different lines and columns. You can enter various visual modes in Vim by using the following key combinations. Character mode : v Line mode : Shift+v Block mode : Ctrl+v Character mode highlights sentences in a block of text. The word VISUAL appears at the bottom of the screen. Press v to enter visual character mode. Shift+v enters line mode. VISUAL LINE appears at the bottom of the screen. Visual block mode is perfect for manipulating data files. Press the Ctrl+v keystroke to enter the visual block from the cursor. VISUAL BLOCK appears at the bottom of the screen. Use the arrow keys to highlight the section to change. NOTE First, take the time to familiarize yourself with the basic Vim capabilities. Then, expand your Vim vocabulary by learning more Vim keystrokes. The exercise for this section uses the vimtutor command. This tutorial, from the vim-enhanced package, is an excellent way to learn the core Vim functions. Vim Configuration Files The /etc/vimrc and ~/.vimrc configuration files alter the behavior of the vim editor for the entire system or for a specific user respectively. Within these configuration files, you can specify behavior such as the default tab spacing, syntax highlighting, color schemes, and more. Modifying the behavior of the vim editor is particularly useful when working with languages such as YAML, which have strict syntax requirements. Consider the following ~/.vimrc file, which sets the default tab stop (denoted by the ts characters) to two spaces while editing YAML files. The file also includes the set number parameter to display line numbers while editing all files. [user@host ~]$ cat ~/.vimrc autocmd FileType yaml setlocal ts=2 set number A complete list of vimrc configuration options is available in the references. Guided Exercise: Edit Text Files from the Shell Prompt Use the vimtutor command to practice basic editing techniques in the vim editor. Outcomes Edit files with Vim. Gain competency in Vim by using the vimtutor command. As the student user on the workstation machine, use the lab command to prepare your system for this exercise. This command prepares your environment and ensures that all required resources are available. [student@workstation ~]$ lab start edit-editfile Instructions 1. Use the ssh command to log in to the servera machine as the student user. 2. [student@workstation ~]$ ssh student@servera 3....output omitted... [student@servera ~]$ 4. Run the vimtutor command. Read the Welcome screen and perform Lesson 1.1. In the presentation, keyboard arrow keys help to navigate the window. Initially, when the vi editor was developed, users could not rely on having arrow keys or working keyboard mappings for arrow keys to move the cursor. Therefore, the vi editor was initially designed to move the cursor by using commands with standard character keys, such as the conveniently grouped h, j, k, and l. Here is a way to remember them: hang back, jump down, kick up, leap forward. [student@servera ~]$ vimtutor 5. In the vimtutor window, perform Lesson 1.2. This lesson teaches how to quit without keeping unwanted changes. All changes are lost. Sometimes it is preferable to lose changes than to leave a critical file in an incorrect state. 6. In the vimtutor window, perform Lesson 1.3. Vim has fast, efficient keystrokes to delete an exact number of words, lines, sentences, or paragraphs. Any editing is possible with the x key for single-character deletion. 7. In the vimtutor window, perform Lesson 1.4. For most editing tasks, the i (insert) key is pressed first. 8. In the vimtutor window, perform Lesson 1.5. The previous lecture taught only the i command to enter edit mode. This lesson demonstrates other available keystrokes to change the cursor placement in insert mode. In insert mode, all typed text changes the file content. 9. In the vimtutor window, perform Lesson 1.6. Type :wq to save the file and quit the editor. 10. In the vimtutor window, read the Lesson 1 Summary. The vimtutor command includes six more multistep lessons. These lessons are not assigned as part of this course, but feel free to explore them to learn more. 11. Return to the workstation system as the student user. 12. [student@servera ~]$ exit 13. logout 14. Connection to servera closed. [student@workstation ~]$ Change the Shell Environment Objectives Set shell variables to run commands, and edit Bash startup scripts to set shell and environment variables to modify the behavior of the shell and programs that are run from the shell. Shell Variable Usage With the Bash shell, you can set shell variables to help to run commands or to modify the behavior of the shell. You can also export shell variables as environment variables, which are automatically copied to programs that are run from that shell. You can use variables for ease of running a command with a long argument, or to apply a common setting to commands that are run from that shell. Shell variables are unique to a particular shell session. If you have two terminal windows open, or two independent login sessions to the same remote server, then you are running two shells. Each shell has its own set of values for its shell variables. Assign Values to Variables Assign a value to a shell variable with the following syntax: [user@host ~]$ VARIABLENAME=value Variable names can contain uppercase or lowercase letters, digits, and the underscore character (_). For example, the following commands set shell variables: [user@host ~]$ COUNT=40 [user@host ~]$ first_name=John [user@host ~]$ file1=/tmp/abc [user@host ~]$ _ID=RH123 Remember, this change affects only the shell that you run the command in, not any other shells that you might be running on that server. You can use the set command to list all shell variables that are currently set. (It also lists all shell functions, which you can ignore.) To improve readability, you can pipe the output to the less command so that you can view it one page at a time. [user@host ~]$ set | less BASH=/bin/bash BASHOPTS=checkwinsize:cmdhist:complete_fullquote:expand_aliases:extglob:extquote\ :force_fignore:globasciiranges:histappend:interactive_comments:login_shell:progc\ omp:promptvars:sourcepath BASHRCSOURCED=Y...output omitted... Retrieve Values with Variable Expansion You can use variable expansion to refer to the value of a variable that you set. To use variable expansion, precede the name of the variable with a dollar sign ($). In the following examples, the variable expansion occurs first and then the echo command prints the rest of the command line that is entered. For example, the following command sets the variable COUNT to 40. [user@host ~]$ COUNT=40 If you enter the echo COUNT command, then it prints the COUNT string. [user@host ~]$ echo COUNT COUNT If you enter instead the echo $COUNT command, then it prints the value of the COUNT variable. [user@host ~]$ echo $COUNT 40 You can also use a variable to refer to a long file name for multiple commands. [user@host ~]$ file1=/tmp/tmp.z9pXW0HqcC [user@host ~]$ ls -l $file1 -rw-------. 1 student student 1452 Jan 22 14:39 /tmp/tmp.z9pXW0HqcC [user@host ~]$ rm $file1 [user@host ~]$ ls -l $file1 total 0 IMPORTANT You can always use curly braces in variable expansion, although they are often unnecessary. In the following example, the echo command tries to expand the nonexistent variable COUNTx, but returns nothing. The command does not report any errors either. [user@host ~]$ echo Repeat $COUNTx Repeat If any trailing characters are next to a variable name, then delimit the variable name with curly braces. In the following example, the echo command now expands the COUNT variable. [user@host ~]$ echo Repeat ${COUNT}x Repeat 40x Configure Bash with Shell Variables Some shell variables are set when Bash starts. You can modify them to adjust the shell's behavior. For example, the HISTFILE, HISTFILESIZE, and HISTTIMEFORMAT shell variables affect the shell history and the history command. The HISTFILE variable specifies which file to save the shell history to, and defaults to the ~/.bash_history file. The HISTFILESIZE variable specifies how many commands to save in that file from the history. The HISTTIMEFORMAT variable defines the time stamp format for every command in the history. This variable does not exist by default. [user@host ~]$ history...output omitted... 6 ls /etc 7 uptime 8 ls -l 9 date 10 history [user@host ~]$ HISTTIMEFORMAT="%F %T " [user@host ~]$ history...output omitted... 6 2022-05-03 04:58:11 ls /etc 7 2022-05-03 04:58:13 uptime 8 2022-05-03 04:58:15 ls -l 9 2022-05-03 04:58:16 date 10 2022-05-03 04:58:18 history 11 2022-05-03 04:59:10 HISTTIMEFORMAT="%F %T " 12 2022-05-03 04:59:12 history Another example is the PS1 variable, which controls the appearance of the shell prompt. If you change this value, then it changes the appearance of your shell prompt. Various special character expansions that the prompt supports are listed in the "PROMPTING" section of the bash(1) man page. [user@host ~]$ PS1="bash\$ " bash$ PS1="[\u@\h \W]\$ " [user@host ~]$ Because the value that the PS1 variable sets is a prompt, Red Hat recommends ending the prompt with a trailing space. Also, whenever a variable value contains some form of space, including a space, a tab, or a return, the value must be enclosed in either single or double quotation marks. Unexpected results might occur if the quotation marks are omitted. The previous PS1 variable conforms to both the trailing space recommendation and the quotation marks rule. Configure Programs with Environment Variables The shell provides an environment for the programs that you run from that shell. Among other items, this environment includes information about the current working directory on the file system, the command-line options that are passed to the program, and the values of environment variables. The programs might use these environment variables to change their behavior or their default settings. If a shell variable is not an environment variable, then only the shell can use it. However, if a shell variable is an environment variable, then the shell and any programs that run from that shell can use the variable. NOTE The HISTFILE, HISTFILESIZE, and PS1 variables from the previous section do not need to be exported as environment variables, because only the shell itself uses them, not the programs that you run from the shell. You can assign any variable that is defined in the shell as an environment variable by marking it for export with the export command. [user@host ~]$ EDITOR=vim [user@host ~]$ export EDITOR You can set and export a variable in one step: [user@host ~]$ export EDITOR=vim Applications and sessions use these variables to determine their behavior. For example, the shell automatically sets the HOME variable to the file name of the user's home directory when it starts. You can use this variable to help programs to determine where to save files. Another example is the LANG variable, which sets the locale encoding. This variable adjusts the preferred language for program output; the character set; the formatting of dates, numbers, and currency; and the sort order for programs. If it is set to en_US.UTF-8, then the locale uses US English with UTF-8 Unicode character encoding. If it is set, for example, to fr_FR.UTF-8, then it uses French UTF-8 Unicode encoding. [user@host ~]$ date Tue Jan 22 16:37:45 CST 2019 [user@host ~]$ export LANG=fr_FR.UTF-8 [user@host ~]$ date mar. janv. 22 16:38:14 CST 2019 Another important environment variable is PATH. The PATH variable contains a list of colon-separated directories that contain programs: [user@host ~]$ echo $PATH /home/user/.local/bin:/home/user/bin:/usr/share/Modules/bin:/usr/local/bin:/usr/bin:/ usr/local/sbin:/usr/sbin When you run a command such as the ls command, the shell looks for the ls executable file in each of those directories in order, and runs the first matching file that it finds. (On a typical system, this file is /usr/bin/ls.) You can append directories to your PATH variable. For example, perhaps you want to run some executable programs or scripts such as regular commands in the /home/user/sbin directory. You can append the /home/user/sbin directory to your PATH for the current session as follows: [user@host ~]$ export PATH=${PATH}:/home/user/sbin To list all the environment variables for a shell, run the env command: [user@host ~]$ env...output omitted... LANG=en_US.UTF-8 HISTCONTROL=ignoredups HOSTNAME=host.example.com XDG_SESSION_ID=4...output omitted... Set the Default Text Editor The EDITOR environment variable specifies your default text editor for command- line programs. Many programs use the vi or vim editor if it is not specified, and you can override this preference: [user@host ~]$ export EDITOR=nano IMPORTANT By convention, environment variables and shell variables that are automatically set by the shell have names with all uppercase characters. If you are setting your own variables, then you might want to use names with lowercase characters to prevent naming collisions. Set Variables Automatically When Bash starts, several text files run with shell commands that initialize the shell environment. To set shell or environment variables automatically when your shell starts, you can edit these Bash startup scripts. The exact scripts that run depend on whether the shell is interactive or non- interactive, and a login or non-login shell. A user directly enters commands into an interactive shell, whereas a non-interactive shell, such as a script, runs in the background without user intervention. A login shell is invoked when a user logs in locally via the terminal or remotely via the SSH protocol. A non-login shell is invoked from an existing session, such as to open a terminal from the GNOME GUI. For interactive login shells, the /etc/profile and ~/.bash_profile files configure the Bash environment. The /etc/profile and ~/.bash_profile files also source the /etc/bashrc and ~/.bashrc files respectively. For interactive non-login shells, only the /etc/bashrc and ~/.bashrc files configure the Bash environment. Whereas the /etc/profile and /etc/bashrc files apply to the whole system, the ~/.bash_profile and ~/.bashrc files are user-specific. Non-interactive shells invoke any files that the BASH_ENV variable defines. This variable is not defined by default. To create a variable that is available to all of your interactive shells, edit the ~/.bashrc file. To apply a variable only once after the user logs in, define it in the ~/.bash_profile file. For example, to change the default editor when you log in via SSH, you can modify the EDITOR variable in your ~/.bash_profile file: #.bash_profile # Get the aliases and functions if [ -f ~/.bashrc ]; then. ~/.bashrc fi # User specific environment and startup programs export EDITOR=nano NOTE The best way to adjust settings that affect all user accounts is to add a file with a.sh extension that contains the changes to the /etc/profile.d directory. To create the files in the /etc/profile.d directory, log in as the root user. Bash Aliases Bash aliases are shortcuts to other Bash commands. For example, if you must often type a long command, then you can create a shorter alias to invoke it. You use the alias command to create aliases. Consider the following example, which creates a hello alias for an echo command. [user@host ~]$ alias hello='echo "Hello, this is a long string."' You can then run the hello command and it invokes the echo command. [user@host ~]$ hello Hello, this is a long string. Add aliases to a user's ~/.bashrc file so they are available in any interactive shell. Unset and Unexport Variables and Aliases To unset and unexport a variable, use the unset command: [user@host ~]$ echo $file1 /tmp/tmp.z9pXW0HqcC [user@host ~]$ unset file1 [user@host ~]$ echo $file1 [user@host ~]$ To unexport a variable without unsetting it, use the export -n command: [user@host ~]$ export -n PS1 To unset an alias, use the unalias command: [user@host ~]$ unalias hello Guided Exercise: Change the Shell Environment Use shell variables and variable expansion to run commands, and set an environment variable to adjust the default editor for new shells. Outcomes Edit a user profile. Create a shell variable. Create an environment variable. As the student user on the workstation machine, use the lab command to prepare your system for this exercise. This command ensures that all required resources are available. [student@workstation ~]$ lab start edit-bashconfig Instructions 1. Change the student user's PS1 shell variable to [\u@\h \t \w]$ (remember to put the value of PS1 in quotation marks and to include a trailing space after the dollar sign). This change adds the time to the prompt. 1. Use the ssh command to log in to servera as the student user. 2. [student@workstation ~]$ ssh student@servera 3....output omitted... [student@servera ~]$ 4. Use Vim to edit the ~/.bashrc configuration file. [student@servera ~]$ vim ~/.bashrc 5. Add the PS1 shell variable and its value to the ~/.bashrc file. Set the value of the shell variable, including a trailing space at the end, inside quotation marks. 6....output omitted... 7. export PATH PS1='[\u@\h \t \w]$ ' 8. Exit from servera and log in again by using the ssh command to update the command prompt, or execute the ~/.bashrc file by using the source ~/.bashrc command. 9. [student@servera ~]$ exit 10. logout 11. Connection to servera closed. 12. [student@workstation ~]$ ssh student@servera 13....output omitted... [student@servera 14:45:05 ~]$ 2. Assign a value to a local shell variable. Variable names can contain uppercase or lowercase letters, digits, and the underscore character. Retrieve the variable value. 1. Create a variable called file with a value of tmp.zdkei083. The tmp.zdkei083 file exists in the student home directory. [student@servera 14:47:05 ~]$ file=tmp.zdkei083 2. Retrieve the value of the file variable. 3. [student@servera 14:48:35 ~]$ echo $file tmp.zdkei083 4. Use the file variable name and the ls -l command to list the tmp.zdkei083 file. Use the rm command and the file variable name to delete the tmp.zdkei083 file. Verify that the file is deleted. 5. [student@servera 14:59:07 ~]$ ls -l $file 6. -rw-r--r--. 1 student student 0 Jan 23 14:59 tmp.zdkei083 7. [student@servera 14:59:10 ~]$ rm $file 8. [student@servera 14:59:15 ~]$ ls -l $file ls: cannot access 'tmp.zdkei083': No such file or directory 3. Assign a value to the EDITOR variable. Use one command to assign the variable as an environment variable. 4. [student@servera 14:46:40 ~]$ export EDITOR=vim 5. [student@servera 14:46:55 ~]$ echo $EDITOR vim 6. Return to the workstation system as the student user. 7. [student@servera 14:47:11 ~]$ exit 8. logout 9. Connection to servera closed. [student@workstation ~]$ Summary Running programs, or processes, have three standard communication channels: standard input, standard output, and standard error. You can use I/O redirection to read standard input from a file or to write the output or errors from a process to a file. Pipelines can connect standard output from one process to the standard input of another process, and can format output or build complex commands. Know how to use at least one command-line text editor, and Vim is the recommended option because it is commonly installed by default in Linux distributions. Shell variables can help you to run commands, and are unique to a shell session. You can modify the behavior of the shell or the processes with environment variables.