🎧 New: AI-Generated Podcasts Turn your study notes into engaging audio conversations. Learn more

LPI-Learning-Material-102-500-en-1.pdf

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Full Transcript

Table of Contents TOPIC 105: SHELLS AND SHELL SCRIPTING................................................ 1 105.1 Customize and use the shell environment........................................ 2 105.1 Lesson 1...................................................................... 4 Introd...

Table of Contents TOPIC 105: SHELLS AND SHELL SCRIPTING................................................ 1 105.1 Customize and use the shell environment........................................ 2 105.1 Lesson 1...................................................................... 4 Introduction...................................................................... 4 Shell Types: Interactive vs. Non-Interactive and Login vs. Non-Login................... 5 Guided Exercises................................................................. 18 Explorational Exercises........................................................... 20 Summary....................................................................... 22 Answers to Guided Exercises...................................................... 24 Answers to Explorational Exercises................................................. 26 105.1 Lesson 2..................................................................... 28 Introduction..................................................................... 28 Variables: Assignment and Reference............................................. 28 Local or Shell Variables......................................................... 32 Global or Environment Variables................................................. 34 Guided Exercises................................................................. 45 Explorational Exercises........................................................... 48 Summary....................................................................... 50 Answers to Guided Exercises...................................................... 52 Answers to Explorational Exercises................................................. 56 105.1 Lesson 3..................................................................... 58 Introduction..................................................................... 58 Creating Aliases............................................................... 58 Creating Functions............................................................. 62 Guided Exercises................................................................. 73 Explorational Exercises........................................................... 76 Summary....................................................................... 77 Answers to Guided Exercises...................................................... 79 Answers to Explorational Exercises................................................. 84 105.2 Customize or write simple scripts............................................... 85 105.2 Lesson 1..................................................................... 87 Introduction..................................................................... 87 Script Structure and Execution................................................... 88 Variables...................................................................... 90 Arithmetic Expressions......................................................... 93 Conditional Execution.......................................................... 94 Script Output.................................................................. 95 Guided Exercises................................................................. 98 Explorational Exercises........................................................... 99 Summary...................................................................... 100 Answers to Guided Exercises..................................................... 101 Answers to Explorational Exercises................................................ 102 105.2 Lesson 2.................................................................... 103 Introduction.................................................................... 103 Extended Tests............................................................... 103 Loop Constructs.............................................................. 108 A More Elaborate Example..................................................... 111 Guided Exercises................................................................ 115 Explorational Exercises.......................................................... 117 Summary...................................................................... 118 Answers to Guided Exercises..................................................... 119 Answers to Explorational Exercises................................................ 121 TOPIC 106: USER INTERFACES AND DESKTOPS........................................... 122 106.1 Install and configure X11...................................................... 123 106.1 Lesson 1.................................................................... 124 Introduction.................................................................... 124 X Window System Architecture................................................. 125 X Server Configuration......................................................... 128 Wayland..................................................................... 133 Guided Exercises................................................................ 135 Explorational Exercises.......................................................... 136 Summary...................................................................... 137 Answers to Guided Exercises..................................................... 138 Answers to Explorational Exercises................................................ 139 106.2 Graphical Desktops........................................................... 140 106.2 Lesson 1.................................................................... 141 Introduction.................................................................... 141 X Window System............................................................. 142 Desktop Environment......................................................... 142 Popular Desktop Environments................................................. 144 Desktop Interoperability....................................................... 146 Non-Local Access............................................................. 147 Guided Exercises................................................................ 149 Explorational Exercises.......................................................... 150 Summary...................................................................... 151 Answers to Guided Exercises..................................................... 152 Answers to Explorational Exercises................................................ 153 106.3 Accessibility.................................................................. 154 106.3 Lesson 1.................................................................... 155 Introduction.................................................................... 155 Accessibility Settings.......................................................... 155 Keyboard and Mouse Assist.................................................... 156 Visual Impairments........................................................... 158 Guided Exercises................................................................ 160 Explorational Exercises.......................................................... 161 Summary...................................................................... 162 Answers to Guided Exercises..................................................... 163 Answers to Explorational Exercises................................................ 164 TOPIC 107: ADMINISTRATIVE TASKS.................................................... 165 107.1 Manage user and group accounts and related system files....................... 166 107.1 Lesson 1.................................................................... 168 Introduction.................................................................... 168 Adding User Accounts......................................................... 168 Modifying User Accounts...................................................... 170 Deleting User Accounts........................................................ 172 Adding, Modifying and Deleting Groups......................................... 172 The Skeleton Directory........................................................ 173 The /etc/login.defs File.................................................... 173 The passwd Command........................................................ 174 The chage Command......................................................... 175 Guided Exercises................................................................ 177 Explorational Exercises.......................................................... 178 Summary...................................................................... 179 Answers to Guided Exercises..................................................... 181 Answers to Explorational Exercises................................................ 183 107.1 Lesson 2.................................................................... 185 Introduction.................................................................... 185 /etc/passwd.................................................................. 186 /etc/group................................................................... 186 /etc/shadow.................................................................. 187 /etc/gshadow................................................................ 188 Filter the Password and Group Databases........................................ 188 Guided Exercises................................................................ 190 Explorational Exercises.......................................................... 192 Summary...................................................................... 193 Answers to Guided Exercises..................................................... 194 Answers to Explorational Exercises................................................ 196 107.2 Automate system administration tasks by scheduling jobs....................... 198 107.2 Lesson 1.................................................................... 200 Introduction.................................................................... 200 Schedule Jobs with Cron....................................................... 200 User Crontabs................................................................ 201 System Crontabs.............................................................. 202 Particular Time Specifications................................................... 203 Crontab Variables............................................................. 203 Creating User Cron Jobs....................................................... 204 Creating System Cron Jobs..................................................... 205 Configure Access to Job Scheduling............................................. 206 An Alternative to Cron......................................................... 206 Guided Exercises................................................................ 209 Explorational Exercises.......................................................... 211 Summary...................................................................... 212 Answers to Guided Exercises..................................................... 213 Answers to Explorational Exercises................................................ 215 107.2 Lesson 2.................................................................... 217 Introduction.................................................................... 217 Schedule Jobs with at......................................................... 217 List Scheduled Jobs with atq................................................... 218 Delete Jobs with atrm......................................................... 219 Configure Access to Job Scheduling............................................. 219 Time Specifications............................................................ 220 An Alternative to at........................................................... 220 Guided Exercises................................................................ 221 Explorational Exercises.......................................................... 222 Summary...................................................................... 223 Answers to Guided Exercises..................................................... 224 Answers to Explorational Exercises................................................ 225 107.3 Localisation and internationalisation.......................................... 227 107.3 Lesson 1.................................................................... 229 Introduction.................................................................... 229 Time Zones.................................................................. 230 Daylight Savings Time......................................................... 234 Language and Character Encoding.............................................. 234 Encoding Conversion.......................................................... 238 Guided Exercises................................................................ 239 Explorational Exercises.......................................................... 240 Summary...................................................................... 241 Answers to Guided Exercises..................................................... 242 Answers to Explorational Exercises................................................ 243 TOPIC 108: ESSENTIAL SYSTEM SERVICES................................................ 244 108.1 Maintain system time......................................................... 245 108.1 Lesson 1.................................................................... 247 Introduction.................................................................... 247 Local Versus Universal Time.................................................... 248 Date........................................................................ 248 Hardware Clock............................................................... 250 timedatectl................................................................... 250 Setting Time Zone Without timedatectl.......................................... 252 Setting Date and Time Without timedatectl....................................... 253 Guided Exercise................................................................ 255 Explorational Exercises.......................................................... 257 Summary...................................................................... 258 Answers to Guided Exercises..................................................... 260 Answers to Explorational Exercises................................................ 262 108.1 Lesson 2.................................................................... 263 Introduction.................................................................... 263 timedatectl................................................................... 264 NTP Daemon................................................................. 266 NTP Configuration............................................................ 266 pool.ntp.org.................................................................. 267 ntpdate...................................................................... 268 ntpq........................................................................ 268 chrony...................................................................... 269 Guided Exercise................................................................ 274 Explorational Exercise........................................................... 276 Summary...................................................................... 277 Answers Guided Exercise........................................................ 278 Answers to Explorational Exercises................................................ 280 108.2 System logging............................................................... 281 108.2 Lesson 1.................................................................... 283 Introduction.................................................................... 283 System Logging.............................................................. 283 Guided Exercises................................................................ 304 Explorational Exercises.......................................................... 306 Summary...................................................................... 307 Answers to Guided Exercises..................................................... 308 Answers to Explorational Exercises................................................ 311 108.2 Lesson 2.................................................................... 312 Introduction.................................................................... 312 Basics of systemd............................................................ 312 The System Journal: systemd-journald........................................ 313 Guided Exercises................................................................ 331 Explorational Exercises.......................................................... 333 Summary...................................................................... 334 Answers to Guided Exercises..................................................... 335 Answers to Explorational Exercises................................................ 337 108.3 Mail Transfer Agent (MTA) basics.............................................. 338 108.3 Lesson 1.................................................................... 339 Introduction.................................................................... 339 Local and Remote MTA........................................................ 339 Linux MTAs.................................................................. 341 The mail Command and Mail User Agents (MUA)................................. 346 Delivery Customization........................................................ 347 Guided Exercises................................................................ 349 Explorational Exercises.......................................................... 350 Summary...................................................................... 351 Answers to Guided Exercises..................................................... 352 Answers to Explorational Exercises................................................ 353 108.4 Manage printers and printing................................................. 354 108.4 Lesson 1.................................................................... 355 Introduction.................................................................... 355 The CUPS Service............................................................. 356 Installing a Printer............................................................ 360 Managing Printers............................................................ 362 Submitting Print Jobs.......................................................... 363 Managing Print Jobs........................................................... 366 Removing Printers............................................................ 367 Guided Exercises................................................................ 368 Explorational Exercises.......................................................... 369 Summary...................................................................... 370 Answers to Guided Exercises..................................................... 372 Answers to Explorational Exercises................................................ 373 TOPIC 109: NETWORKING FUNDAMENTALS............................................. 375 109.1 Fundamentals of internet protocols............................................ 376 109.1 Lesson 1.................................................................... 377 Introduction.................................................................... 377 IP (Internet Protocol).......................................................... 377 Guided Exercises................................................................ 386 Explorational Exercises.......................................................... 387 Summary...................................................................... 388 Answers to Guided Exercises..................................................... 389 Answers to Explorational Exercises................................................ 390 109.1 Lesson 2.................................................................... 391 Introduction.................................................................... 391 Transmission Control Protocol (TCP)............................................. 393 User Datagram Protocol (UDP).................................................. 393 Internet Control Message Protocol (ICMP)........................................ 393 IPv6......................................................................... 393 Guided Exercises................................................................ 397 Explorational Exercises.......................................................... 398 Summary...................................................................... 399 Answers to Guided Exercises..................................................... 400 Answers to Explorational Exercises................................................ 401 109.2 Persistent network configuration.............................................. 402 109.2 Lesson 1.................................................................... 403 Introduction.................................................................... 403 The Network Interface......................................................... 403 Interface Names.............................................................. 405 Interface Management........................................................ 406 Local and Remote Names...................................................... 408 Guided Exercises................................................................ 412 Explorational Exercises.......................................................... 413 Summary...................................................................... 414 Answers to Guided Exercises..................................................... 415 Answers to Explorational Exercises................................................ 416 109.2 Lesson 2.................................................................... 417 Introduction.................................................................... 417 NetworkManager............................................................. 417 systemd-networkd............................................................ 421 Guided Exercises................................................................ 425 Explorational Exercises.......................................................... 426 Summary...................................................................... 427 Answers to Guided Exercises..................................................... 428 Answers to Explorational Exercises................................................ 429 109.3 Basic network troubleshooting................................................ 430 109.3 Lesson 1.................................................................... 432 Introduction.................................................................... 432 About the ip Command....................................................... 432 Netmask and Routing Review.................................................. 433 Configuring an Interface....................................................... 434 The Routing Table............................................................. 437 Guided Exercises................................................................ 440 Explorational Exercises.......................................................... 441 Summary...................................................................... 442 Answers to Guided Exercises..................................................... 443 Answers to Explorational Exercises................................................ 445 109.3 Lesson 2.................................................................... 447 Introduction.................................................................... 447 Testing Connections With ping................................................. 447 Tracing Routes............................................................... 448 Finding MTUs With tracepath................................................. 450 Creating Arbitrary Connections................................................. 451 Viewing Current Connections and Listeners...................................... 453 Guided Exercises................................................................ 455 Explorational Exercises.......................................................... 456 Summary...................................................................... 457 Answers to Guided Exercises..................................................... 458 Answers to Explorational Exercises................................................ 460 109.4 Configure client side DNS..................................................... 462 109.4 Lesson 1.................................................................... 463 Introduction.................................................................... 463 Name Resolution Process...................................................... 463 DNS Classes.................................................................. 464 Name Resolution Tools........................................................ 467 Guided Exercises.............................................................. 473 Explorational Exercises........................................................ 474 Summary...................................................................... 475 Answers to Guided Exercises................................................... 476 Answers to Explorational Exercises.............................................. 477 TOPIC 110: SECURITY................................................................. 478 110.1 Perform security administration tasks......................................... 479 110.1 Lesson 1.................................................................... 481 Introduction.................................................................... 481 Checking for Files with the SUID and SGID Set.................................... 481 Password Management and Aging.............................................. 484 Discovering Open Ports........................................................ 487 Limits on Users Logins, Processes and Memory Usage............................. 494 Dealing with Logged in Users................................................... 496 Basic sudo Configuration and Usage............................................ 499 Guided Exercises................................................................ 504 Explorational Exercises.......................................................... 507 Summary...................................................................... 508 Answers to Guided Exercises..................................................... 510 Answers to Explorational Exercises................................................ 514 110.2 Setup host security........................................................... 515 110.2 Lesson 1.................................................................... 516 Introduction.................................................................... 516 Improve Authentication Security with Shadow Passwords.......................... 516 How to Use a Superdaemon to Listen for Incoming Network Connections............ 518 Checking Services for Unnecessary Daemons..................................... 523 TCP Wrappers as Sort of a Simple Firewall........................................ 525 Guided Exercises................................................................ 526 Explorational Exercises.......................................................... 527 Summary...................................................................... 528 Answers to Guided Exercises..................................................... 530 Answers to Explorational Exercises................................................ 531 110.3 Securing data with encryption................................................. 532 110.3 Lesson 1.................................................................... 534 Introduction.................................................................... 534 Basic OpenSSH Client Configuration and Usage................................... 535 The Role of OpenSSH Server Host Keys.......................................... 540 SSH Port Tunnels............................................................. 542 Guided Exercises................................................................ 546 Explorational Exercises.......................................................... 548 Summary...................................................................... 549 Answers to Guided Exercises..................................................... 550 Answers to Explorational Exercises................................................ 552 110.3 Lesson 2.................................................................... 553 Introduction.................................................................... 553 Perform Basic GnuPG Configuration, Usage and Revocation........................ 553 Use GPG to Encrypt, Decrypt, Sign and Verify Files................................. 559 Guided Exercises................................................................ 564 Explorational Exercises.......................................................... 566 Summary...................................................................... 567 Answers to Guided Exercises..................................................... 568 Answers to Explorational Exercises................................................ 570 Imprint............................................................................ 571 LPIC-1 (102) (Version 5.0) | Topic 105: Shells and Shell Scripting Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 1 LPIC-1 (102) (Version 5.0) | Topic 105: Shells and Shell Scripting 105.1 Customize and use the shell environment Reference to LPI objectives LPIC-1 version 5.0, Exam 102, Objective 105.1 Weight 4 Key knowledge areas Set environment variables (e.g. PATH) at login or when spawning a new shell. Write Bash functions for frequently used sequences of commands. Maintain skeleton directories for new user accounts. Set command search path with the proper directory. Partial list of the used files, terms and utilities. source /etc/bash.bashrc /etc/profile env export set unset ~/.bash_profile ~/.bash_login 2 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 105.1 Customize and use the shell environment ~/.profile ~/.bashrc ~/.bash_logout function alias Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 3 LPIC-1 (102) (Version 5.0) | Topic 105: Shells and Shell Scripting 105.1 Lesson 1 Certificate: LPIC-1 Version: 5.0 Topic: 105 Shells and Shell Scripting Objective: 105.1 Customize and use the shell environment Lesson: 1 of 3 Introduction The shell is arguably the most powerful tool in a Linux system and can be defined as an interface between the user and the kernel of the operating system. It interprets commands entered by the user. Therefore, all system administrators must be skilled in using the shell. As we may certainly know by now, the Bourne Again Shell (Bash) is the de facto shell for the vast majority of Linux distributions. Once started, the first thing Bash — or any other shell for that matter — does is executing a series of startup scripts. These scripts customize the session’s environment. There are both system wide and user specific scripts. We can put our personal preferences or settings that best fit our users' needs in these scripts in the form of variables, aliases and functions. The exact series of startup files depends on a very important parameter: the type of shell. Let us have a look at the variety of shells that exist. 4 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 105.1 Customize and use the shell environment Shell Types: Interactive vs. Non-Interactive and Login vs. Non- Login To start with, let us clarify the concepts of interactive and login in the context of shells: Interactive / Non-interactive Shells This kind of shell refers to the interaction that takes place between the user and the shell: The user provides input by typing commands into the terminal using the keyboard; the shell provides output by printing messages on the screen. Login / Non-login Shells This kind of shell refers to the event of a user accessing a computer system providing its credentials, such as username and password. Both interactive and non-interactive shells can be either login or non-login and any possible combination of these types has its specific uses. Interactive login shells are executed when users log into the system and are used to customize users' configurations according to their needs. A good example of this type of shell would be that of a group of users belonging to the same department who need a particular variable set in their sessions. By interactive non-login shells we refer to any other shells opened by the user after logging into the system. Users use these shells during sessions to carry out maintenance and administrative tasks such as setting variables, the time, copying files, writing scripts, etc. On the other hand, non-interactive shells do not require any kind of human interaction. Thus, these shells do not ask the user for input and their output — if any — is in most cases written to a log. Non-interactive login shells are quite rare and impractical. Their uses are virtually non-existent and we will only comment on them for the sake of insight into shell behaviour. Some odd examples include forcing a script to be run from a login shell with /bin/bash --login or piping the standard output (stdout) of a command into the standard input (stdin) of an ssh connection: | ssh @ As for non-interactive non-login shell there is neither interaction nor login on behalf of the user, so we are referring here to the use of automated scripts. These scripts are mostly used to carry out Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 5 LPIC-1 (102) (Version 5.0) | Topic 105: Shells and Shell Scripting repetitive administrative and maintenance tasks such as those included in cronjobs. In such cases, bash does not read any startup files. Opening a Terminal When we are in a desktop environment, we can either open a terminal application or switch to one of the system consoles. Therefore, a new shell is either a pts shell when opened from a terminal emulator in the GUI or a tty shell when run from a system console. In the first case we are not dealing with a terminal but with a terminal emulator. As part of graphical sessions, terminal emulators like gnome-terminal or konsole are very feature-rich and user-friendly as compared to text-based user interface terminals. Less feature-rich terminal emulators include — amongst others — XTerm and sakura. Using the Ctrl + Alt + F1 - F6 combos we can go to the console logins which open an interactive text- based login shell. Ctrl + Alt + F7 will take the session back into the Desktop. tty stands for teletypewritter; pts stands for pseudo terminal slave. For more NOTE information: man tty and man pts. Launching Shells with bash After logging in, type bash into a terminal to open a new shell. Technically, this shell is a child process of the current shell. While starting the bash child process, we can specify various switches to define which kind of shell we want to start. Here some important bash invocation options: bash -l or bash --login will invoke a login shell. bash -i will invoke an interactive shell. bash --noprofile with login shells will ignore both the system-wide startup file /etc/profile and the user-level startup files ~/.bash_profile, ~/.bash_login and ~/.profile. bash --norc with interactive shells will ignore both the system-wide startup file /etc/bash.bashrc and the user-level startup file ~/.bashrc. 6 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 105.1 Customize and use the shell environment bash --rcfile with interactive shells will take as the startup file ignoring system wide /etc/bash.bashrc and user-level ~/.bashrc. We will discus the various startup files below. Launching Shells with su and sudo Through the use of these two similar programs we can obtain specific types of shells: su Change user ID or become superuser (root). With this command we can invoke both login and non-login shells: su - user2, su -l user2 or su --login user2 will start an interactive login shell as user2. su user2 will start an interactive non-login shell as user2. su - root or su - will start an interactive login shell as root. su root or su will start an interactive non-login shell as root. sudo Execute commands as another user (including the supersuser). Because this command is mainly used to gain root privileges temporarily, the user using it must be in the sudoers file. To add users to sudoers we need to become root and then run: root@debian:~# usermod -aG sudo user2 Just as su, sudo allows us to invoke both login and non-login shells: sudo su - user2, sudo su -l user2 or sudo su --login user2 will start an interactive login shell as user2. sudo su user2 will start an interactive non-login shell as user2. sudo -u user2 -s will start an interactive non-login shell as user2. sudo su - root or sudo su - will start an interactive login shell as root. sudo -i will start an interactive login shell as root. sudo -i will start an interactive login shell as root, run the command and return to the original user. Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 7 LPIC-1 (102) (Version 5.0) | Topic 105: Shells and Shell Scripting sudo su root or sudo su will start an interactive non-login shell as root. sudo -s or sudo -u root -s will start a non-login shell as root. When using either su or sudo, it is important to consider our particular case scenario for starting a new shell: Do we need the target user’s environment or not? If so, we would use the options which invoke login shells; if not, those which invoke non-login shells. What Shell Type Do We Have? In order to find out what type of shell we are working at, we can type echo $0 into the terminal and get the following output: Interactive login -bash or -su Interactive non-login bash or /bin/bash Non-interactive non-login (scripts) How Many Shells Do We Have? To see how many bash shells we have up and running in the system, we can use the command ps aux | grep bash: user2@debian:~$ ps aux | grep bash user2 5270 0.1 0.1 25532 5664 pts/0 Ss 23:03 0:00 bash user2 5411 0.3 0.1 25608 5268 tty1 S+ 23:03 0:00 -bash user2 5452 0.0 0.0 16760 940 pts/0 S+ 23:04 0:00 grep --color=auto bash user2 at debian has logged into a GUI (or X Window System) session and opened gnome-terminal, then she has pressed Ctrl + Alt + F1 to go into a tty terminal session. Finally, she has gone back to the GUI session by pressing Ctrl + Alt + F7 and typed in the command ps aux | grep bash. Thus, the output shows an interactive non-login shell via the terminal emulator (pts/0) and an interactive login shell via the proper text-based terminal (tty1). Note also how the last field of each line (the command) is bash for the former and -bash for the latter. 8 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 105.1 Customize and use the shell environment Where Shells Get their Configuration From: Startup Files Well, now that we know the shell types that we can find in a Linux system, it is high time that we saw what startup files get executed by what shell. Note that system wide or global scripts are placed in the /etc/ directory, whereas local or user-level ones are found in the user’s home (~). Also, when there is more than one file to be searched, once one is found and run the others are ignored. Explore and study these files yourself with your favorite text editor or by typing less. Startup files can be divided into Bash specific (those limited only to bash NOTE configurations and commands) and general ones (relating to most shells). Interactive Login Shell Global Level /etc/profile This is the system-wide.profile file for the Bourne shell and Bourne compatible shells (bash included). Through a series of if statements this file sets a number of variables such as PATH and PS1 accordingly as well as sourcing — if they exist — both the file /etc/bash.bashrc and those in the directory /etc/profile.d. /etc/profile.dcopyright. Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent permitted by applicable law. Last login: Tue Nov 27 19:57:19 2018 from 192.168.1.10 Hello from /etc/profile Hello from /home/user2/.profile As the last two lines show, it worked. Also, note three things: The global file was run first. There were no.bash_profile or.bash_login files in he home directory of user2. The tilde (~) expanded to the absolute path of the file (/home/user2/.profile). 10 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 105.1 Customize and use the shell environment Interactive Non-Login Shell Global Level /etc/bash.bashrc This is the system-wide.bashrc file for interactive bash shells. Through its execution bash makes sure it is being run interactively, checks the window size after each command (updating the values of LINES and COLUMNS if necessary) and sets some variables. Local Level ~/.bashrc In addition to carrying out similar tasks to those described for /etc/bash.bashrc at a user level (such as checking the window size or if being run interactively), this Bash specific file usually sets some history variables and sources ~/.bash_aliases if it exists. Apart from that, this file is normally used to store users' specific aliases and functions. Likewise, it is also worthwhile noting that ~/.bashrc is read if bash detects its is a network connection (as it was the case with the Secure Shell (SSH) connection in the example above). Exploring Interactive Non-Login Shell Configuration Files Let us now modify /etc/bash.bashrc and /home/user2/.bashrc: root@debian:~# echo 'echo Hello from /etc/bash.bashrc' >> /etc/bash.bashrc root@debian:~# echo 'echo Hello from ~/.bashrc' >> ~/.bashrc And this is what happens when user2 starts a new shell: user2@debian:~$ bash Hello from /etc/bash.bashrc Hello from /home/user2/.bashrc Again, the two files were read and executed. Remember, because of the order in which files are run, local files take WARNING precedence over global ones. Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 11 LPIC-1 (102) (Version 5.0) | 105.1 Customize and use the shell environment the exact distribution terms for each program are described in the individual files in /usr/share/doc chameleon **/ Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 45 LPIC-1 (102) (Version 5.0) | Topic 105: Shells and Shell Scripting Wrong Command Right Command Variable Reference Expected Output win_path=C:\path\t C:\path\to\dir\ o\dir\ 4. Consider the purpose and write the appropriate command: Purpose Command Set the language of the current shell to Spanish UTF-8 (es_ES.UTF-8). Print the name of the current working directory. Reference the environment variable which stores the information about ssh connections. Set PATH to include /home/carol/scripts as the last directory to search for executables. Set the value of my_path to PATH. Set the value of my_path to that of PATH. 5. Create a local variable named mammal and assign it the value gnu: 6. Using variable substitution, create another local variable named var_sub with the appropriate value so that when referenced via echo $var_sub we obtain: The value of mammal is gnu: 7. Turn mammal into an environment variable: 8. Search for it with set and grep: 9. Search for it with env and grep: 10. Create, in two consecutive commands, an environment variable named BIRD whose value is penguin: 46 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 105.1 Customize and use the shell environment 11. Create, in a single command, an environment variable named NEW_BIRD whose value is yellow-eyed penguin: 12. Assuming you are user2, create a folder named bin in your home directory: 13. Type the command to add the ~/bin folder to your PATH so that it is the first directory bash searches for binaries: 14. To guarantee the value of PATH remains unaltered across reboots, what piece of code — in the form of an if statement — would you put into ~/.profile? Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 47 LPIC-1 (102) (Version 5.0) | Topic 105: Shells and Shell Scripting Explorational Exercises 1. let: more than arithmetic expression evaluation: ◦ Do a manpage or web search for let and its implications when setting variables and create a new local variable named my_val whose value is 10 — as a result of adding 5 and 5: ◦ Now create another variable named your_val whose value is 5 — as a result of dividing the value of my_val into 2: 2. The result of a command in a variable? Of course, that is possible; it is called command substitution. Investigate it and study the following function named music_info: music_info(){ latest_music=`ls -l1t ~/Music | head -n 6` echo -e "Your latest 5 music files:\n$latest_music" } The result of the command ls -l1t ~/Music | head -n 6 becomes the value of the variable latest_music. Then the variable latest_music is referenced in the echo command (which outputs the total number of bytes occupied by the Music folder and the latest five music files stored in the Music folder — one per line). Which of the following is a valid synonym for latest_music=`ls -l1t ~/Music | head -n 6` Option A: latest_music=$(ls -l1t ~/Music| head -n 6) Option B: latest_music="(ls -l1t ~/Music| head -n 6)" Option C: 48 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 105.1 Customize and use the shell environment latest_music=((ls -l1t ~/Music| head -n 6)) Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 49 LPIC-1 (102) (Version 5.0) | Topic 105: Shells and Shell Scripting Summary In this lesson we learned: Variables are a very important part of the shell environment as they are used by the shell itself as well as by other programs. How to assign and reference variables. The differences between local and global (or environment) variables. How to make variables readonly. How to turn a local variable into an environment variable with the export command. How to list all environment variables. How to run a program in a modified environment. How to make variables persistent with the help of startup scripts. Some common environment variables: DISPLAY, HISTCONTROL, HISTSIZE, HISTFILESIZE, HISTFILE, HOME, HOSTNAME, HOSTTYPE, LANG, LD_LIBRARY_PATH, MAIL, MAILCHECK, PATH, PS1 (and other prompt variables), SHELL and USER. The meaning of the tilde (~). The very basics of if statements. Commands used in this lesson: echo Reference a variable. ls List directory contents. readonly Make variables immutable. List all readonly variables in current session. set List all variables and functions in current session. grep Print lines matching a pattern. 50 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 105.1 Customize and use the shell environment bash Launch a new shell unset Unset variables. export Turn a local variable into an environment variable. List environment variables. env List environment variables. Run a program in a modified environment. printenv List environment variables. Reference a variable. chmod Change mode bits of a file, for example make it executable. history List previous commands. su Change user ID or become superuser. id Print user ID. Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 51 LPIC-1 (102) (Version 5.0) | Topic 105: Shells and Shell Scripting Answers to Guided Exercises 1. Observe the variable assignment under the “Command(s)” column and indicate if the resulting variable is “Local” or “Global”: Command(s) Local Global debian=mother Yes No ubuntu=deb-based Yes No mint=ubuntu-based; No Yes export mint export suse=rpm-based No Yes zorin=ubuntu-based Yes No 2. Study the “Command” and the “Output” and explain the meaning: Command Output Meaning echo $HISTCONTROL ignoreboth Both duplicate commands and those starting with a space will not be saved in history. echo ~ /home/carol The HOME of carol is /home/carol. echo $DISPLAY reptilium:0:2 reptilium machine has a X server running and we are using the second screen of the display. echo $MAILCHECK 60 Mail will be checked every minute. echo $HISTFILE /home/carol/.bash_histor history will be saved in y /home/carol/.bash_histor y. 3. Variables are being set incorrectly under the “Wrong Command” column. Provide the missing information under “Right Command” and “Variable Reference” so that we get the “Expected Output”: 52 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 105.1 Customize and use the shell environment Wrong Command Right Command Variable Reference Expected Output lizard =chameleon lizard=chameleon echo $lizard chameleon cool cool_lizard=chamel echo $cool_lizard chameleon lizard=chameleon eon (for example) lizard=cha|me|leon lizard="cha|me|leo echo $lizard cha|me|leon n" or lizard='cha|me|leo n' lizard= chameleon **/ chameleon **/" or lizard='' win_path=C:\path\t win_path=C:\\path\ echo $win_path C:\path\to\dir\ o\dir\ \to\\dir\\ 4. Consider the purpose and write the appropriate command: Purpose Command Set the language of the current shell to LANG=es_ES.UTF-8 Spanish UTF-8 (es_ES.UTF-8). Print the name of the current working echo $PWD or pwd directory Reference the environment variable which echo $SSH_CONNECTION stores the information about ssh connections Set PATH to include /home/carol/scripts as PATH=$PATH:/home/carol/scripts the last directory to search for executables. Set the value of my_path to PATH. my_path=PATH Set the value of my_path to that of PATH. my_path=$PATH 5. Create a local variable named mammal and assign it the value gnu: mammal=gnu 6. Using variable substitution, create another local variable named var_sub with the appropriate value so that when referenced via echo $var_sub we obtain The value of mammal is gnu: Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 53 LPIC-1 (102) (Version 5.0) | Topic 105: Shells and Shell Scripting var_sub="The value of mammal is $mammal" 7. Turn mammal into an environment variable: export mammal 8. Search for it with set and grep: set | grep mammal 9. Search for it with env and grep: env | grep mammal 10. Create, in two consecutive commands, an environment variable named BIRD whose value is penguin: BIRD=penguin; export BIRD 11. Create, in a single command, an environment variable named NEW_BIRD whose value is yellow-eyed penguin: export NEW_BIRD="yellow-eyed penguin" or export NEW_BIRD='yellow-eyed penguin' 12. Assuming you are user2, use mkdir to create a folder named bin in your home directory: mkdir ~/bin or mkdir /home/user2/bin 54 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 105.1 Customize and use the shell environment or mkdir $HOME/bin 13. Type the command to add the ~/bin folder to your PATH so that it is the first directory bash searches for binaries: PATH="$HOME/bin:$PATH" PATH=~/bin:$PATH or PATH=/home/user2/bin:$PATH are equally valid. 14. To guarantee the value of PATH remains unaltered across reboots, what piece of code — in the form of an if statement — would you put into ~/.profile? if [ -d "$HOME/bin" ] ; then PATH="$HOME/bin:$PATH" fi Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 55 LPIC-1 (102) (Version 5.0) | Topic 105: Shells and Shell Scripting Answers to Explorational Exercises 1. let: more than arithmetic expression evaluation: ◦ Do a manpage or web search for let and its implications when setting variables and create a new local variable named my_val whose value is 10 — as a result of adding 5 and 5: let "my_val = 5 + 5" or let 'my_val = 5 + 5' ◦ Now create another variable named your_val whose value is 5 — as a result of dividing the value of my_val into 2: let "your_val = $my_val / 2" or let 'your_val = $my_val / 2' 2. The result of a command in a variable? Of course, that is possible; it is called command substitution. Investigate it and study the following function named music_info: music_info(){ latest_music=`ls -l1t ~/Music | head -n 6` echo -e "Your latest 5 music files:\n$latest_music" } The result of the command ls -l1t ~/Music | head -n 6 becomes the value of the variable latest_music. Then the variable latest_music is referenced in the echo command (which outputs the total number of bytes occupied by the Music folder and the latest five music files stored in the Music folder — one per line). Which of the following is a valid synonym for 56 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 105.1 Customize and use the shell environment latest_music=`ls -l1t ~/Music | head -n 6` It is option A: latest_music=$(ls -l1t ~/Music| head -n 6) Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 57 LPIC-1 (102) (Version 5.0) | Topic 105: Shells and Shell Scripting 105.1 Lesson 3 Certificate: LPIC-1 Version: 5.0 Topic: 105 Shells and Shell Scripting Objective: 105.1 Customize and use the shell environment Lesson: 3 of 3 Introduction After going through shells, startup scripts and variables in the previous lessons, we will round the whole topic of customizing the shell off by having a look at two very interesting shell elements: aliases and functions. In fact the entire group of variables, aliases and functions — and their influence on one another — is what makes up the shell environment. The main strength of these two flexible and time-saving shell facilities has to do with the concept of encapsulation: they offer the possibility of putting together — under a single command — a series of repetitive or recurrent commands. Creating Aliases An alias is a substitute name for another command(s). It can run like a regular command, but instead executes another command according to the alias definition. The syntax for declaring aliases is quite straightforward. Aliases are declared by writing the keyword alias followed by the alias assignment. In turn, the alias assignment consists of the alias name, an equal sign and one or more commands: 58 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 105.1 Customize and use the shell environment alias alias_name=command(s) For example: $ alias oldshell=sh This awkward alias will start an instance of the original sh shell when the user types oldshell into the terminal: $ oldshell $ The power of aliases lies in that they allow us to write short versions of long commands: $ alias ls='ls --color=auto' NOTE For information about ls and its colors, type man dir_colors into the terminal. Likewise, we can create aliases for a series of concatenated commands — the semicolon (;) is used as a delimiter. We can, for instance, have an alias that gives us information about the location of the git executable and its version: $ alias git_info='which git;git --version' To invoke an alias, we type its name into the terminal: $ git_info /usr/bin/git git version 2.7.4 The alias command will produce a listing of all available aliases in the system: $ alias alias git-info='which git;git --version' alias ls='ls --color=auto' alias oldshell='sh' Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 59 LPIC-1 (102) (Version 5.0) | Topic 105: Shells and Shell Scripting The unalias command removes aliases. We can, for instance, unalias git-info and see how it disappears from the listing: $ unalias git-info $ alias alias ls='ls --color=auto' alias oldshell='sh' As we saw with the alias hi='echo We salute you.' in a previous lesson, we must enclose commands in quotes (either single or double) when — as a result of having arguments or parameters — they contain spaces: $ alias greet='echo Hello world!' $ greet Hello world! Commands with spaces include also those with options: $ alias ll='ls -al' Now ll will list all files — including the hidden ones (a) — in the long format (l). We can reference variables in aliases: $ reptile=uromastyx $ alias greet='echo Hello $reptile!' $ greet Hello uromastyx! The variable can also be assigned within the alias: $ alias greet='reptile=tortoise; echo Hello $reptile!' $ greet Hello tortoise! We can escape an alias with \: $ alias where?='echo $PWD' 60 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 105.1 Customize and use the shell environment $ where? /home/user2 $ \where? -bash: where?: command not found Escaping an alias is useful when an alias has the same name as a regular command. In this case, the alias takes precedence over the original command, which, however, is still be accessible by escaping the alias. Likewise, we can put an alias inside another alias: $ where? /home/user2 $ alias my_home=where? $ my_home /home/user2 On top of that, we can also put a function inside an alias as you will be shown below. Expansion and Evaluation of Quotes in Aliases When using quotes with environment variables, single quotes make the expansion dynamic: $ alias where?='echo $PWD' $ where? /home/user2 $ cd Music $ where? /home/user2/Music However, with double quotes the expansion is done statically: $ alias where?="echo $PWD" $ where? /home/user2 $ cd Music $ where? /home/user2 Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 61 LPIC-1 (102) (Version 5.0) | Topic 105: Shells and Shell Scripting Persistence of Aliases: Startup Scripts Just as with variables, for our aliases to gain persistence, we must put them into initialization scripts that are sourced at startup. As we already know, a good file for users to put their personal aliases in is ~/.bashrc. You will probably find some aliases there already (most of them commented out and ready to be used by removing the leading #): $ grep alias.bashrc # enable color support of ls and also add handy aliases alias ls='ls --color=auto' #alias dir='dir --color= #alias vdir='vdir --color= #alias grep='grep --color= #alias fgrep='fgrep --color' #alias egrep='egrep --color= # some more ls aliases #ll='ls -al' #alias la='ls -A' #alias l='ls -CF' # ~/.bash_aliases, instead of adding them here directly. if [ -f ~/.bash_aliases ]; then. ~/.bash_aliases As you can read in the last three lines, we are offered the possibility of having our own alias- dedicated file — ~/.bash_aliases — and have it sourced by.bashrc with every system start. So we can go for that option and create and populate such file: ########### #.bash_aliases: # a file to be populated by the user's personal aliases (and sourced by ~/.bashrc). ########### alias git_info='which git;git --version' alias greet='echo Hello world!' alias ll='ls -al' alias where?='echo $PWD' Creating Functions Compared to aliases, functions are more programmatic and flexible, specially when it comes to exploiting the full potential of Bash special built-in variables and positional parameters. They are also great to work with flow control structures such as loops or conditionals. We can think of a 62 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 105.1 Customize and use the shell environment function as a command which includes logic through blocks or collections of other commands. Two Syntaxes for Creating Functions There are two valid syntaxes to define functions. Using the keyword function On the one hand, we can use the keyword function, followed by the name of the function and the commands between curly brackets: function function_name { command #1 command #2 command #3... command #n } Using () On the other, we can leave out the keyword function and use two brackets right after the name of the function instead: function_name() { command #1 command #2 command #3... command #n } It is commonplace to put functions in files or scripts. However, they can also be written directly into the shell prompt with each command on a different line — note PS2(>) indicating a new line after a line break: $ greet() { > greeting="Hello world!" Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 63 LPIC-1 (102) (Version 5.0) | Topic 105: Shells and Shell Scripting > echo $greeting > } Whatever the case — and irrespective of the syntax we choose — , if we decide to skip line breaks and write a function in just one line, commands must be separated by semicolons (note the semicolon after the last command too): $ greet() { greeting="Hello world!"; echo $greeting; } bash did not complain when we pressed Enter, so our function is ready to be invoked. To invoke a function, we must type its name into the terminal: $ greet Hello world! Just as with variables and aliases, if we want functions to be persistent across system reboots we have to put them into shell initialization scripts such as /etc/bash.bashrc (global) or ~/.bashrc (local). After adding aliases or functions to any startup script file, you should source WARNING such files with either. or source for the changes to take effect if you do not want to logout and back in again or reboot the system. Bash Special Built-in Variables The Bourne Again Shell comes with a set of special variables which are particularly useful for functions and scripts. These are special because they can only be referenced — not assigned. Here is a list of the most relevant ones: $? This variable’s reference expands to the result of the last command run. A value of 0 means success: $ ps aux | grep bash user2 420 0.0 0.4 21156 5012 pts/0 Ss 17:10 0:00 -bash user2 640 0.0 0.0 12784 936 pts/0 S+ 18:04 0:00 grep bash $ echo $? 0 64 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 105.1 Customize and use the shell environment A value other than 0 means error: user1@debian:~$ ps aux |rep bash -bash: rep: command not found user1@debian:~$ echo $? 127 $$ It expands to the shell PID (process ID): $ ps aux | grep bash user2 420 0.0 0.4 21156 5012 pts/0 Ss 17:10 0:00 -bash user2 640 0.0 0.0 12784 936 pts/0 S+ 18:04 0:00 grep bash $ echo $$ 420 $! It expands to the PID of the last background job: $ ps aux | grep bash & 663 $ user2 420 0.0 0.4 21156 5012 pts/0 Ss+ 17:10 0:00 -bash user2 663 0.0 0.0 12784 972 pts/0 S 18:08 0:00 grep bash ^C + Done ps aux | grep bash $ echo $! 663 NOTE Remember, the ampersand (&) is used to start processes in the background. Positional parameters $0 through $9 They expand to the parameters or arguments being passed to the function (alias or script) — $0 expanding to the name of the script or shell. Let us create a function to demonstrate positional parameters — note PS2 (>) indicating new lines after line breaks: $ special_vars() { > echo $0 > echo $1 Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 65 LPIC-1 (102) (Version 5.0) | Topic 105: Shells and Shell Scripting > echo $2 > echo $3 } Now, we will invoke the function (special_vars) passing three parameters to it (debian, ubuntu, zorin): $ special_vars debian ubuntu zorin -bash debian ubuntu zorin It worked as expected. Although passing positional parameters to aliases is technically possible, it is not at all functional since — with aliases — positional parameters are always passed at the end: WARNING $ alias great_editor='echo $1 is a great text editor' $ great_editor emacs is a great text editor emacs Other Bash special built-in variables include: $# It expands to the number of arguments passed to the command. $@, $* They expand to the arguments passed to the command. $_ It expands to the last parameter or the name of the script (amongst other things; see man bash to find out more!): Variables in Functions Of course, variables can be used within functions. To prove it, this time we will create a new empty file called funed and put the following function 66 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 105.1 Customize and use the shell environment into it: editors() { editor=emacs echo "My editor is: $editor. $editor is a fun text editor." } As you may have guessed by now, we must source the file first to be able to invoke the function: $. funed And now we can test it: $ editors My editor is emacs. emacs is a fun text editor. As you can appreciate, for the editors function to work properly, the editor variable must first be set. The scope of that variable is local to the current shell and we can reference it as long as the session lasts: $ echo $editor emacs Together with local variables we can also include environment variables in our function: editors() { editor=emacs echo "The text editor of $USER is: $editor." } editors Note how this time we decided to call the function from within the file itself (editors in the last line). That way, when we source the file, the function will also be invoked — all at once: Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 67 LPIC-1 (102) (Version 5.0) | Topic 105: Shells and Shell Scripting $. funed The text editor of user2 is: emacs. Positional Parameters in Functions Something similar occurs with positional parameters. We can pass them to functions from within the file or script (note the last line: editors tortoise): editors() { editor=emacs echo "The text editor of $USER is: $editor." echo "Bash is not a $1 shell." } editors tortoise We source the file and prove it works: $. funed The text editor of user2 is: emacs. Bash is not a tortoise shell. And we can also pass positional parameters to functions at the command line. To prove it, we get rid of the last line of the file: editors() { editor=emacs echo "The text editor of $USER is: $editor." echo "Bash is not a $1 shell." } Then, we have to source the file: 68 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 105.1 Customize and use the shell environment $. funed Finally, we invoke the function with tortoise as the positional parameter $1 at the command line: $ editors tortoise The text editor of user2 is: emacs. Bash is not a tortoise shell. Functions in Scripts Functions are mostly found in Bash scripts. Turning our funed file into a script (we will name it funed.sh) is really a piece of cake: #!/bin/bash editors() { editor=emacs echo "The text editor of $USER is: $editor." echo "Bash is not a $1 shell." } editors tortoise That is it! We only added two lines: The first line is the shebang and defines what program is going to interpret the script: #!/bin/bash. Curiously enough, that program is bash itself. The last line is simply the invocation of the function. Now there is only one thing left — we have to make the script executable: $ chmod +x funed.sh And now it is ready to be executed: Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 69 LPIC-1 (102) (Version 5.0) | Topic 105: Shells and Shell Scripting $./funed.sh The text editor of user2 is: emacs. Bash is not a tortoise shell. NOTE You will learn all about shell scripting in the next few lessons. A Function within an Alias As said above, we can put a function inside an alias: $ alias great_editor='gr8_ed() { echo $1 is a great text editor; unset -f gr8_ed; }; gr8_ed' This long alias value deserves an explanation. Let us break it down: First there is the function itself: gr8_ed() { echo $1 is a great text editor; unset -f gr8_ed; } The last command in the function — unset -f gr8_ed — unsets the function so that it does not remain in the present bash session after the alias is called. Last but not least, to have a successful alias invocation, we must first invoke the function too: gr8_ed. Let us invoke the alias and prove it works: $ great_editor emacs emacs is a great text editor As shown in unset -f gr8_ed above, the unset command is not only used to unset variables, but also functions. In fact, there are specific switches or options: unset -v for variables unset -f for functions If used without switches, unset will try to unset a variable first and — if it fails — then it will try to unset a function. 70 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 105.1 Customize and use the shell environment A Function within a Function Now say we want to communicate two things to user2 every time she logs into the system: Say hello and recommend/praise a text editor. Since she is starting to put a lot of Matroska video files in its $HOME/Video folder, we also want to give her a warning. To accomplish that purpose, we have put the following two functions into /home/user2/.bashrc: The first function (check_vids) does the checking on.mkv files and the warning: check_vids() { ls -1 ~/Video/*.mkv > /dev/null 2>&1 if [ "$?" = "0" ];then echo -e "Remember, you must not keep more than 5 video files in your Video folder.\nThanks." else echo -e "You do not have any videos in the Video folder. You can keep up to 5.\nThanks." fi } check_vids does three things: It lists the mkv files in ~/Video sending the output — and any errors — to the so-called bit- bucket (/dev/null). It tests the output of the previous command for success. Depending on the result of the test, it echoes one of two messages. The second function is a modified version of our editors function: editors() { editor=emacs echo "Hi, $USER!" echo "$editor is more than a text editor!" check_vids } Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 71 LPIC-1 (102) (Version 5.0) | Topic 105: Shells and Shell Scripting editors It is important to observe two things: The last command of editors invokes check_vids so both functions get chained: The greeting, praise and the checking and warning are executed in sequence. editors itself is the entry point to the sequence of functions so it is invoked in the last line (editors). Now, let us log in as user2 and prove it works: # su - user2 Hi, user2! emacs is more than a text editor! Remember, you must not keep more than 5 video files in your Video folder. Thanks. 72 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 105.1 Customize and use the shell environment Guided Exercises 1. Complete the table with “Yes” or “No” considering the capabilities of aliases and functions: Feature Aliases? Functions? Local variables can be used Environment variables can be used Can be escaped with \ Can be recursive Very productive when used with positional parameters 2. Enter the command that list all aliases in your system: 3. Write an alias named logg that lists all ogg files in ~/Music — one per line: 4. Invoke the alias to prove it works: 5. Now, modify the alias so that it echoes out the session’s user and a colon before the listing: 6. Invoke it again to prove this new version also works: 7. List all aliases again and check your logg alias appears in the listing: 8. Remove the alias: 9. Study the columns “Alias Name” and “Aliased Command(s)`” and assign the aliases to their values correctly: Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 73 LPIC-1 (102) (Version 5.0) | Topic 105: Shells and Shell Scripting Alias Name Aliased Command(s) Alias Assignment b bash bash_info which bash + echo "$BASH_VERSION" kernel_info uname -r greet echo Hi, $USER! computer pc=slimbook + echo My computer is a $pc 10. As root, write a function called my_fun in /etc/bash.bashrc. The function must say hello to the user and tell them what their path is. Invoke it so that the user gets both messages every time they log in: 11. Login as user2 to check it works: 12. Write the same function in just one line: 13. Invoke the function: 14. Unset the function: 15. This is a modified version of the special_vars function: $ special_vars2() { > echo $# > echo $_ > echo $1 > echo $4 > echo $6 > echo $7 > echo $_ > echo $@ > echo $? 74 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 105.1 Customize and use the shell environment > } This is the command we use to invoke it: $ special_vars2 crying cockles and mussels alive alive oh Guess the outputs: Reference Value echo $# echo $_ echo $1 echo $4 echo $6 echo $7 echo $_ echo $@ echo $? 16. Based on the sample function (check_vids) in the section “A Function within a Function”, write a function named check_music to include into a bash startup script that accepts positional parameters so that we can modify easily: ◦ the type of file being checked: ogg ◦ the directory in which files are saved: ~/Music ◦ the type of file being kept: music ◦ the number of files being saved: 7 Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 75 LPIC-1 (102) (Version 5.0) | Topic 105: Shells and Shell Scripting Explorational Exercises 1. Read-only functions are those whose contents we cannot modify. Do a research on readonly functions and complete the following table: Function Name Make it readonly List all readonly Functions my_fun 2. Search the web for how to modify PS1 and anything else you may need to write a function called fyi (to be placed in a startup script) which gives the user the following information: ◦ name of the user ◦ home directory ◦ name of the host ◦ operating system type ◦ search path for executables ◦ mail directory ◦ how often mail is checked ◦ how many shells deep the current session is ◦ prompt (you should modify it so that it shows @) 76 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 105.1 Customize and use the shell environment Summary In this lesson you learned: Both aliases and functions are important features of the shell that allow us to encapsulate recurrent blocks of code. Aliases are useful to have shorter versions of long and/or complicated commands. Functions are procedures that implement logic and allow us to automate tasks, specially when used in scripts. The syntax to write aliases and functions. How to concatenate various commands by means of the semicolon (;). How to properly use quotes with aliases. How to make aliases and functions persistent. Bash special built-in variables: $?, $$, $!, positional parameters ($0-$9), $#, $@, $* and $_. How to use variables and positional parameters with functions. How to use functions in scripts. How to invoke a function from an alias. How to invoke a function from another function. The basics for creating a bash script. Commands and keywords used in this lesson: alias Create aliases. unalias Remove aliases. cd Change directory. grep Print lines matching a pattern. function Shell keyword to create functions. Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 77 LPIC-1 (102) (Version 5.0) | Topic 105: Shells and Shell Scripting. Source a file. source Source a file. ps Report a snapshot of the current processes. echo Display a line of text. chmod Change mode bits of a file, for example make it executable. unset Unset variables and functions. su Change user ID or become superuser. 78 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 105.1 Customize and use the shell environment Answers to Guided Exercises 1. Complete the table with “Yes” or “No” considering the capabilities of aliases and functions: Feature Aliases? Functions? Local variables can be used Yes Yes Environment variables can be Yes Yes used Can be escaped with \ Yes No Can be recursive Yes Yes Very productive when used No Yes with positional parameters 2. Enter the command that list all aliases in your system: alias 3. Write an alias named logg that lists all ogg files in ~/Music — one per line: alias logg='ls -1 ~/Music/*ogg' 4. Invoke the alias to prove it works: logg 5. Now, modify the alias so that it echoes out the session’s user and a colon before the listing: alias logg='echo $USER:; ls -1 ~/Music/*ogg' 6. Invoke it again to prove this new version also works: logg 7. List all aliases again and check your logg alias appears in the listing: Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 79 LPIC-1 (102) (Version 5.0) | Topic 105: Shells and Shell Scripting alias 8. Remove the alias: unalias logg 9. Study the columns “Alias Name” and “Aliased Command(s)” and assign the aliases to their values correctly: Alias Name Aliased Command(s) Alias Assignment b bash alias b=bash bash_info which bash + echo alias bash_info='which "$BASH_VERSION" bash; echo "$BASH_VERSION"' kernel_info uname -r alias kernel_info='uname -r' greet echo Hi, $USER! alias greet='echo Hi, $USER' computer pc=slimbook + echo My alias computer is a $pc computer='pc=slimbook; echo My computer is a $pc' NOTE Single quotes can also be replaced by double ones. 10. As root, write a function called my_fun in /etc/bash.bashrc. The function must say hello to the user and tell them what their path is. Invoke it so that the user gets both messages every time they log in: Option A: my_fun() { echo Hello, $USER! echo Your path is: $PATH } my_fun 80 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 105.1 Customize and use the shell environment Option B: function my_fun { echo Hello, $USER! echo Your path is: $PATH } my_fun 11. Login as user2 to check it works: su - user2 12. Write the same function in just one line: Option A: my_fun() { echo "Hello, $USER!"; echo "Your path is: $PATH"; } Option B: function my_fun { echo "Hello, $USER!"; echo "Your path is: $PATH"; } 13. Invoke the function: my_fun 14. Unset the function: unset -f my_fun 15. This is a modified version of the special_vars function: $ special_vars2() { > echo $# > echo $_ > echo $1 > echo $4 > echo $6 Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 81 LPIC-1 (102) (Version 5.0) | Topic 105: Shells and Shell Scripting > echo $7 > echo $_ > echo $@ > echo $? > } This is the command we use to invoke it: $ special_vars2 crying cockles and mussels alive alive oh Guess the outputs: Reference Value echo $# 7 echo $_ 7 echo $1 crying echo $4 mussels echo $6 alive echo $7 oh echo $_ oh echo $@ crying cockles and mussels alive alive oh echo $? 0 16. Based on the sample function (check_vids) in section “A Function within a Function”, write a function named check_music to include into a bash startup script that accepts positional

Use Quizgecko on...
Browser
Browser