NET-212 (NDG Linux Chapter 5)

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

5.4 Variables

A variable is a feature that allows the user or the shell to store data. This data can be used to provide critical system information or to change the behavior of how the Bash shell (or other commands) work. Variables are given names and stored temporarily in memory. There are two types of variables used in the Bash shell: local and environment.

5.5.3 Step 3

Aliases can be used to map longer commands to shorter key sequences. When the shell sees an alias being executed, it substitutes the longer sequence before proceeding to interpret commands. To determine what aliases are set on the current shell, use the alias command: sysadmin@localhost:~$ alias alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"' alias egrep='egrep --color=auto' alias fgrep='fgrep --color=auto' alias grep='grep --color=auto' alias l='ls -CF alias la='ls -A' alias ll='ls -alF' alias ls='ls --color=auto'

5.5.1 Internal Commands

Also called built-in commands, internal commands are built into the shell itself. A good example is the cd (change directory) command as it is part of the Bash shell. When a user types the cd command, the Bash shell is already executing and knows how to interpret it, requiring no additional programs to be started. The type command identifies the cd command as an internal command: sysadmin@localhost:~$ type cd cd is a shell builtin

5.5.3 Aliases

An alias can be used to map longer commands to shorter key sequences. When the shell sees an alias being executed, it substitutes the longer sequence before proceeding to interpret commands. For example, the command ls -l is commonly aliased to l or ll. Because these smaller commands are easier to type, it becomes faster to run the ls -l command line. To determine what aliases are set on the current shell use the alias command: sysadmin@localhost:~$ alias alias egrep='egrep --color=auto' alias fgrep='fgrep --color=auto' alias grep='grep --color=auto' alias l='ls -CF' alias la='ls -A' alias ll='ls -alF' alias ls='ls --color=auto' The aliases from the previous examples were created by initialization files. These files are designed to make the process of creating aliases automatic. New aliases can be created using the following format, where name is the name to be given the alias and command is the command to be executed when the alias is run. alias name=command For example, the cal 2019 command displays the calendar for the year 2019. Suppose you end up running this command often. Instead of executing the full command each time, you can create an alias called mycal and run the alias, as demonstrated in the following graphic: sysadmin@localhost:~$ alias mycal="cal 2019" sysadmin@localhost:~$ mycal 2019 January Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 February Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 March Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Aliases created this way only persist while the shell is open. Once the shell is closed, the new aliases are lost. Additionally, each shell has its own aliases, so aliases created in one shell won't be available in a new shell that's opened. The type command can identify aliases to other commands: sysadmin@localhost:~$ type ll ll is aliased to `ls -alF' sysadmin@localhost:~$ type -a ls ls is aliased to `ls --color=auto' ls is /bin/ls The output of these commands indicates that ll is an alias for ls -alF, and even ls is an alias for ls --color=auto.

5.2.2 Step 2

Arguments can be added to commands as well. Adding the location of a specific directory to the ls command will list information for that directory. Use the argument /tmp to display detailed information about files in the /tmp directory. ls -l /tmp Your output should be similar to the following: sysadmin@localhost:~$ ls -l /tmp total 0 -rw-rw-r-- 1 root root 1863 Oct 31 19:47 inside_setup.sh By using the option -l and the argument /tmp, we can now see that the /tmp directory has a file called inside_setup.sh located inside it.

5.6.4 Backquotes

Backquotes, or backticks, are used to specify a command within a command, a process called command substitution. This allows for powerful and sophisticated use of commands. While it may sound confusing, an example should make things more clear. To begin, note the output of the date command: sysadmin@localhost:~$ date Mon Nov 4 03:35:50 UTC 2018 Now, note the output of the echo command: sysadmin@localhost:~$ echo Today is date Today is date In the previous command, the word date is treated as regular text, and the shell passes date to the echo command. To execute the date command and have the output of that command sent to the echo command, put the date command in between two backquote characters: sysadmin@localhost:~$ echo Today is `date` Today is Mon Nov 4 03:40:04 UTC 2018

type

Command that determines information about command type.

echo

Command that displays output in the terminal.

history

Command that outputs a list of previously executed commands.

export

Command that turns a local variable into an environment variable.

5.7 Control Statements

Control statements allow you to use multiple commands at once or run additional commands, depending on the success of a previous command. Typically these control statements are used within scripts, but they can also be used on the command line as well.

5.6.5 Step 5

Double quote characters don't have any effect on backquote characters. The shell will still use them as command substitution. Execute the following to see a demonstration: echo This is the command "`date`" Your output should be similar to the following: sysadmin@localhost:~$ echo This is the command "`date`" This is the command Mon Dec 3 21:37:33 UTC 2018

5.6.6 Step 6

Double quote characters will have an effect on wildcard characters, disabling their special meaning. Execute the following: echo D* echo "D*" Your output should be similar to the following: sysadmin@localhost:~$ echo D* Desktop Documents Downloads sysadmin@localhost:~$ echo "D*" D* sysadmin@localhost:~$ Important Quoting may seem trivial and weird at the moment, but as you gain more experience working in the command shell, you will discover that having a good understanding of how different quotes work is critical to using the shell.

5.6.1 Double Quotes

Double quotes stop the shell from interpreting some metacharacters (special characters), including glob characters. Glob characters, also called wild cards, are symbols that have special meaning to the shell; they are interpreted by the shell itself before it attempts to run any command. Glob characters include the asterisk * character, the question ? mark character, and the brackets [ ], among others. Globbing will be covered in greater detail later in the course. Within double quotes an asterisk is just an asterisk, a question mark is just a question mark, and so on, which is useful when you want to display something on the screen that is normally a special character to the shell. In the echo command below, the Bash shell doesn't convert the glob pattern into filenames that match the pattern: sysadmin@localhost:~$ echo "The glob characters are *, ? and [ ]" The glob characters are *, ? and [ ] Double quotes still allow for command substitution, variable substitution, and permit some other shell metacharacters that haven't been discussed yet. The following demonstration shows that the value of the PATH variable is still displayed: sysadmin@localhost:~$ echo "The path is $PATH" The path is /usr/bin/custom:/home/sysadmin/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games

5.4.2 Step 2

Environment variables are available system-wide. The system automatically recreates environment variables when a new shell is opened. Examples include the PATH, HOME, and HISTSIZE variables. The HISTSIZE variable defines how many previous commands to store in the history list. In the example below, the command will display the value of the HISTSIZE variable: sysadmin@localhost:~$ echo $HISTSIZE‌ 1000 sysadmin@localhost:~$

5.4.2 Environment Variables

Environment variables, also called global variables, are available system-wide, in all shells used by Bash when interpreting commands and performing tasks. The system automatically recreates environment variables when a new shell is opened. Examples include the PATH, HOME, and HISTSIZE variables. The HISTSIZE variable defines how many previous commands to store in the history list. The command in the example below displays the value of the HISTSIZE variable: sysadmin@localhost:~$ echo $HISTSIZE 1000 To modify the value of an existing variable, use the assignment expression: sysadmin@localhost:~$ HISTSIZE=500 sysadmin@localhost:~$ echo $HISTSIZE 500 Many variables are available for the Bash shell, as well as variables that affect different Linux commands. A discussion of all variables is beyond the scope of this chapter; however, more shell variables will be covered as this course progresses. When run without arguments, the env command outputs a list of the environment variables. Because the output of the env command can be quite long, the following examples use a text search to filter that output. In a previous example variable1 was created as a local variable, so the following search in the environment variables results in no output: sysadmin@localhost:~$ env | grep variable1 The pipe | character passes the output of the env command to the grep command, which searches the output. This text filtering technique will be covered in detail later in the course. The export command is used to turn a local variable into an environment variable. export variable After exporting variable1, it is now an environment variable. It is now found in the search through the environment variables: sysadmin@localhost:~$ export variable1 sysadmin@localhost:~$ env | grep variable1 variable1=Something The export command can also be used to make a variable an environment variable upon its creation by using the assignment expression as the argument: sysadmin@localhost:~$ export variable2='Else' sysadmin@localhost:~$ env | grep variable2 variable2=Else To change the value of an environment variable, use the assignment expression: sysadmin@localhost:~$ variable1=$variable1' '$variable2 sysadmin@localhost:~$ echo $variable1 Something Else Exported variables can be removed using the unset command: sysadmin@localhost:~$ unset variable2

5.3.1 Step 1

Execute a new command and then execute the history command: echo Hi history Remember The date command will print the time and date on the system. The clear command clears the screen. Your output should be similar to the following: sysadmin@localhost:~$ history 1 ls 2 ls -l 3 ls -l /tmp 4 whoami 5 uname 6 uname -n 7 uname --nodename 8 pwd 9 echo Hi 10 history sysadmin@localhost:~$ Your command numbers may differ from those provided above. This is because you may have executed a different number of commands since opening the virtual terminal.

5.6.1 Step 1

Execute the following command to use back quotes ` (found under the ~ character on some keyboards) to execute the date command within the line of the echo command: echo Today is `date` Your output should be similar to the following: sysadmin@localhost:~$ echo Today is `date` Today is Mon Dec 3 21:29:45 UTC 2018

5.7.1 Step 1

Execute the following three commands together separated by semicolons: echo Hello; echo Linux; echo Student As you can see the output shows all three commands executed sequentially: sysadmin@localhost:~$ echo Hello; echo Linux; echo Student Hello Linux Student sysadmin@localhost:~$

5.5.2 Step 2

External commands are binary executables stored in directories that are searched by the shell. If a user types the ls command, the shell searches through the directories that are listed in the PATH variable to try to find a file named ls that it can execute. Use the which command to display the full path to the ls command. which ls sysadmin@localhost:~$ which ls /bin/ls For external commands, the type command displays the location of the command: sysadmin@localhost:~$ type cp cp is /bin/cp In some cases the output of the type command may differ significantly from the output of the which command: sysadmin@localhost:~$ which cp /bin/cp Using the -a option of the type command displays all locations that contain the command: sysadmin@localhost:~$ type -a ls ls is aliased to `ls --color=auto' ls is /bin/ls

5.5.2 External Commands

External commands are binary executables stored in directories that are searched by the shell. If a user types the ls command, then the shell searches through the directories that are listed in the PATH variable to try to find a file named ls that it can execute. If a command does not behave as expected or if a command is not accessible that should be, it can be beneficial to know where the shell is finding the command or which version it is using. It would be tedious to have to manually look in each directory that is listed in the PATH variable. Instead, use the which command to display the full path to the command in question: which command The which command searches for the location of a command by searching the PATH variable. sysadmin@localhost:~$ which ls /bin/ls sysadmin@localhost:~$ which cal /usr/bin/cal External commands can also be executed by typing the complete path to the command. For example, to execute the ls command: sysadmin@localhost:~$ /bin/ls Desktop Documents Downloads Music Pictures Public Templates Videos For external commands, the type command displays the location of the command: sysadmin@localhost:~$ type cal cal is /usr/bin/cal In some cases the output of the type command may differ significantly from the output of the which command: sysadmin@localhost:~$ type echo echo is a shell builtin sysadmin@localhost:~$ which echo /bin/echo Using the -a option of the type command displays all locations that contain the command named: sysadmin@localhost:~$ type -a echo echo is a shell builtin echo is /bin/echo

5.5.4 Functions

Functions can also be built using existing commands to either create new commands, or to override commands built-in to the shell or commands stored in files. Aliases and functions are normally loaded from the initialization files when the shell first starts. Functions are more advanced than aliases and typically are used in Bash shell scripts. Typically, functions are used to execute multiple commands. To create a function, the following syntax is used: function_name () { commands } In the format above, function_name can be anything that the administrator wants to call the function. The commands that the administrator wants to execute can replace the commands placeholder. Note the formatting, in particular, the location of the parenthesis () and braces {}, as well as the convention of using tabs to make the function more easily readable. Functions are useful as they allow for a set of commands to be executed one at a time instead of typing each command repeatedly. In the example below, a function called my_report is created to execute the ls, date, and echo commands. sysadmin@localhost:~$ my_report () { > ls Documents > date > echo "Document directory report" > } When creating a function, a > character will appear as a prompt to enter the commands for the function. The curly braces {} are used to let the shell know when a function begins and ends so as to exit the > prompt. Once a function is created, the function name may be invoked from the BASH prompt to execute the function: sysadmin@localhost:~$ my_report School alpha-third.txt hidden.txt numbers.txt spelling.txt Work alpha.txt letters.txt os.csv words adjectives.txt animals.txt linux.txt people.csv alpha-first.txt food.txt longfile.txt profile.txt alpha-second.txt hello.sh newhome.txt red.txt Wed Oct 13 06:54:04 UTC 2021 Document directory report sysadmin@localhost:~$

5.6.3 Step 3

If you don't want the backquotes to be used to execute a command, place single quotes around them. Execute the following: echo This is the command '`date`' Your output should be similar to the following: sysadmin@localhost:~$ echo This is the command '`date`' This is the command `date` sysadmin@localhost:~$

5.5 Command Types

In this section we will learn about the four types of commands used in Linux. Understanding where these commands come from and how they differ allows an administrator to manage the system more effectively.

5.4.1 Local Variables

Local or shell variables exist only in the current shell, and cannot affect other commands or applications. When the user closes a terminal window or shell, all of the variables are lost. They are often associated with user-based tasks and are lowercase by convention. To set the value of a variable, use the following assignment expression. If the variable already exists, the value of the variable is modified. If the variable name does not already exist, the shell creates a new local variable and sets the value: variable=value The following example creates a local variable named variable1 and assigns it a value of Something: sysadmin@localhost:~$ variable1='Something' The echo command is used to display output in the terminal. To display the value of the variable, use a dollar sign $ character followed by the variable name as an argument to the echo command: sysadmin@localhost:~$ echo $variable1 Something

5.1 Introduction

Most consumer operating systems are designed to shield the user from the ins and outs of the CLI. The Linux community is different in that it positively celebrates the CLI for its power, speed and ability to accomplish a vast array of tasks with a single command line instruction. When a user first encounters the CLI, they can find it challenging because it requires memorizing a dizzying amount of commands and their options. However, once a user has learned the structure of how commands are used, where the necessary files and directories are located and how to navigate the hierarchy of a file system, they can be immensely productive. This capability provides more precise control, greater speed and the ability to automate tasks more easily through scripting. Furthermore, by learning the CLI, a user can easily be productive almost instantly on ANY flavor or distribution of Linux, reducing the amount of time needed to familiarize themselves with a system because of variations in a GUI.

5.3.4 Step 4

Next, experiment with accessing your history using the up arrow keys and down arrow keys. Keep pressing the up arrow key until you find a command you want to execute. If necessary, use other keys to edit the command and then press Enter to execute the command.

5.7.3 Step 3

Next, use logical "and" to separate the commands: echo Start && echo Going && echo Gone Your output should be similar to the following: sysadmin@localhost:~$ echo Start && echo Going && echo Gone Start Going Gone sysadmin@localhost:~$ Because each echo statement executes correctly, a return value of success is provided, allowing the next statement to also be executed.

5.6.4 Step 4

Note that you could also place a backslash character in front of each backquote character. Execute the following: echo This is the command \`date\` Your output should be similar to the following: sysadmin@localhost:~$ echo This is the command \`date\` This is the command `date` sysadmin@localhost:~$

5.7.2 Step 2

Now, put three commands together separated by semicolons, where the first command executes with a failure result: false; echo Not; echo Conditional Your output should be similar to the following: sysadmin@localhost:~$ false; echo Not; echo Conditional Not Conditional sysadmin@localhost:~$ Note that in the previous example, all three commands still executed even though the first one failed. While you can't see from the output of the false command, it did execute. However, when commands are separated by the ; character, they are completely independent of each other.

5.2 Shell

Once a user has entered a command the terminal then accepts what the user has typed and passes it to a shell. The shell is the command line interpreter that translates commands entered by a user into actions to be performed by the operating system. If output is produced by the command, then text is displayed in the terminal. If problems with the command are encountered, an error message is displayed. The Linux environment allows the use of many different shells, some of which have been around for many years. The most commonly-used shell for Linux distributions is called the Bash shell. Bash provides many advanced features, such as command history and inline editing, which allows a user to easily re-execute previously executed commands or a variation of them via simple editing. The Bash shell also has other popular features, a few of which are listed below: Scripting: The ability to place commands in a file and then interpret (effectively use Bash to execute the contents of) the file, resulting in all of the commands being executed. This feature also has some programming features, such as conditional statements and the ability to create functions (AKA subroutines). Aliases: The ability to create short nicknames for longer commands. Variables: Used to store information for the Bash shell and for the user. These variables can be used to modify how commands and features work as well as provide vital system information. Bash has an extensive feature list; this is only a sampling of its capabilities. When a terminal application is run, and a shell appears, displaying an important part of the interface—the prompt. Not only is the prompt there to indicate that commands can be run, but it also conveys useful information to the user. The prompt is fully configurable and can be as sparse or as full-featured as is practical and useful. The structure of the prompt may vary between distributions, but typically contains information about the user and the system. Below is a common prompt structure: On cards 3-7. The ~ symbol is used as shorthand for the user's home directory. Typically the home directory for the user is under the /home directory and named after the user account name; for example, /home/sysadmin.

5.4.3 Path Variable

One of the most important Bash shell variables to understand is the PATH variable. It contains a list that defines which directories the shell looks in to find commands. If a valid command is entered and the shell returns a "command not found" error, it is because the Bash shell was unable to locate a command by that name in any of the directories included in the path. The following command displays the path of the current shell: sysadmin@localhost:~$ echo $PATH /home/sysadmin/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games sysadmin@localhost:~$ Each directory in the list is separated by a colon : character. Based on the preceding output, the path contains the following directories. The shell will check the directories in the order they are listed: /home/sysadmin/bin /usr/local/sbin /usr/local/bin /usr/sbin /usr/bin /sbin /bin /usr/games Each of these directories is represented by a path. A path is a list of directories separated by the / character. If you think of the filesystem as a map, paths are the directory addresses, which include step-by-step navigation directions; they can be used to indicate the location of any file within the filesystem. For example, /home/sysadmin is a path to the home directory: Directories and paths will be covered in detail later in the course. If the command is not found in any directory listed in the PATH variable, then the shell returns an error: sysadmin@localhost:~$ zed -bash: zed: command not found sysadmin@localhost:~$ ‌⁠​​⁠​ If custom software is installed on the system it may be necessary to modify the PATH to make it easier to execute these commands. For example, the following will add and verify the /usr/bin/custom directory to the PATH variable: sysadmin@localhost:~$ PATH=/usr/bin/custom:$PATH sysadmin@localhost:~$ echo $PATH /usr/bin/custom:/home/sysadmin/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games When updating the PATH variable, always include the current path, so as not to lose access to commands located in those directories. This can be accomplished by appending $PATH to the value in the assignment expression. Recall that a variable name preceded by a dollar sign represents the value of the variable.

5.5 Command Types

One way to learn more about a command is to look at where it comes from. The type command can be used to determine information about command type. type command There are several different sources of commands within the shell of your CLI including internal commands, external commands, aliases, and functions.

5.5.1 Step 1

One way to learn more about a command is to look at where it comes from. The type command can be used to determine information about command type. type command There are several different sources of commands within the shell of your CLI: Internal commands are built into the shell itself. A good example is the cd (change directory) command as it is part of the Bash shell. When a user types the cd command, the Bash shell is already executing and knows how to interpret it, requiring no additional programs to be started. The type command identifies the cd command as an internal command: sysadmin@localhost:~$ type cd cd is a shell builtin

5.6 Quoting

Quotation marks are used throughout Linux administration and most computer programming languages to let the system know that the information contained within the quotation marks should either be ignored or treated in a way that is very different than it would normally be treated. There are three types of quotes that have special significance to the Bash shell: double quotes ", single quotes ', and back quotes `. Each set of quotes alerts the shell not to treat the text within the quotes in the normal way.

5.4 Shell Variables

Shell variables are used to store data in Linux. This data is used by the shell itself as well as by programs and users. The focus of this section is to learn how to display the values of shell variables.

5.6.2 Single Quotes

Single quotes prevent the shell from doing any interpreting of special characters, including globs, variables, command substitution and other metacharacters that have not been discussed yet. For example, to make the $ character simply mean a $, rather than it acting as an indicator to the shell to look for the value of a variable, execute the second command displayed below: sysadmin@localhost:~$ echo The car costs $100 The car costs 00 sysadmin@localhost:~$ echo 'The car costs $100' The car costs $100

5.7.5 Step 5

The "or" characters separating the following commands demonstrates how the failure before the "or" statement causes the command after it to execute; however, a successful first statement causes the command to not execute: false || echo Fail Or true || echo Nothing to see here Your output should be similar to the following: sysadmin@localhost:~$ false || echo Fail Or Fail Or sysadmin@localhost:~$ true || echo Nothing to see here sysadmin@localhost:~$

5.3 Command History

The Bash shell maintains a history of the commands that you type. Previous commands can be easily accessed in this history in several ways. The first and easiest way to recall a previous command is to use the up arrow key. Each press of the up arrow key goes backwards one command through your command history. If you accidentally go back too far, then the down arrow key will go forwards through the history of commands. When you find the command that you want to execute, you can use the left arrow keys and right arrow keys to position the cursor for editing. Other useful keys for editing include the Home, End, Backspace and Delete keys. Another way to use your command history is to execute the history command to be able to view a numbered history list. The number listed to the left of the command can be used to execute the command again. The history command also has a number of options and arguments which can manipulate which commands will be stored or displayed.

Aliases

The ability to create short nicknames for longer commands.

Scripting

The ability to place commands in a file and then interpret (effectively use Bash to execute the contents of) the file, resulting in all of the commands being executed. This feature also has some programming features, such as conditional statements and the ability to create functions (AKA subroutines).

5.4.1 Step 1

The echo command can be used to print text and the value of a variable, and to show how the shell environment expands metacharacters (more on metacharacters later in this lab). Type the following command to have it output literal text: echo Hello Student Your output should be similar to the following: sysadmin@localhost:~$ echo Hello Student Hello Student sysadmin@localhost:~$

5.5.4 Step 4

The final command type is the executable program. These commands invoke programs installed on the system which perform specific tasks. When a user types the vi command, the shell uses the PATH file to locate and execute the program. Programs like vi are available on just about every Linux distribution; other programs, like vlc (an open source media player often used on Linux desktops), are installed by users or administrators for a specific purpose and will not be listed in the PATH unless they have been installed separately. type vi cd /bin type vlc cd sysadmin@localhost:~$ type vi vi is /usr/bin/vi sysadmin@localhost:~$ cd /bin sysadmin@localhost:/bin$ type vlc -bash: type: vlc: not found sysadmin@localhost:/bin$ cd sysadmin@localhost:~$

5.2.3 Step 3

The following command will display the same information that you see in the first part of the prompt. Make sure that you have selected (clicked on) the Terminal window first and then type the following command followed by the Enter key: whoami Your output should be similar to the following: sysadmin@localhost:~$ whoami sysadmin sysadmin@localhost:~$ The output of the whoami command, sysadmin, displays the user name of the current user. Although in this case your username is displayed in the prompt, this command could be used to obtain this information in a situation when the prompt did not contain this information.

5.2.1 Step 1 ls command

The ls command is used to list information about directories and files and by default it displays information for the current directory. Use the -l option to display this information in the long format, which gives additional information about files located in the current working directory: ls -l Your output should be similar to the following: drwxr-xr-x 2 sysadmin sysadmin 4096 Oct 31 19:52 Desktop drwxr-xr-x 4 sysadmin sysadmin 4096 Oct 31 19:52 Documents drwxr-xr-x 2 sysadmin sysadmin 4096 Oct 31 19:52 Downloads drwxr-xr-x 2 sysadmin sysadmin 4096 Oct 31 19:52 Music drwxr-xr-x 2 sysadmin sysadmin 4096 Oct 31 19:52 Pictures drwxr-xr-x 2 sysadmin sysadmin 4096 Oct 31 19:52 Public drwxr-xr-x 2 sysadmin sysadmin 4096 Oct 31 19:52 Templates drwxr-xr-x 2 sysadmin sysadmin 4096 Oct 31 19:52 Videos

Bash

The most commonly used shell for Linux distributions.

5.2.4 Step 4

The next command displays information about the current system. To be able to see the name of the kernel you are using, type the following command into the terminal: uname Your output should be similar to the following: sysadmin@localhost:~$ uname Linux Many commands that are executed produce text output like this. You can change what output is produced by a command by using options after the name of the command. Options for a command can be specified in several ways. Traditionally in UNIX, options were expressed by a hyphen followed by another character; for example: -n. In Linux, options can sometimes also be given by two hyphen characters followed by a word, or hyphenated word; for example: --nodename. Execute the uname command again twice in the terminal, once with the option -n and again with the option --nodename. This will display the network node hostname, also found in the prompt. uname -n uname --nodename Your output should be similar to the following: sysadmin@localhost:~$ uname -n localhost sysadmin@localhost:~$ uname --nodename localhost

5.2.5 Step 5

The pwd command is used to display your current "location" or current "working" directory. Type the following command to display the working directory: pwd Your output should be similar to the following: sysadmin@localhost:~$ pwd /home/sysadmin sysadmin@localhost:~$ The current directory in the example above is /home/sysadmin. This is also referred to as your home directory, a special place where you have control of files and other users normally have no access. By default, this directory is named the same as your username and is located underneath the /home directory. As you can see from the output of the command, /home/sysadmin, Linux uses the forward slash / to separate directories to make what is called a path. The initial forward slash represents the top-level directory, known as the root directory. More information regarding files, directories and paths will be presented in later labs. The tilde ~ character that you see in your prompt is also indicating what the current directory is. This character is a "shortcut" way to represent your home. Consider This pwd stands for "print working directory". While it doesn't actually "print" in modern versions, older UNIX machines didn't have monitors so the output of commands went to a printer, hence the somewhat misleading name of pwd.

5.6 Quoting

There are three types of quotes used by the Bash shell: single quotes ('), double quotes (") and back quotes (`). These quotes have special features in the Bash shell as described below. To understand single and double quotes, consider that there are times that you don't want the shell to treat some characters as special. For example, the * character is used as a wildcard. What if you wanted the * character to just mean a literal asterisk? Single ' quotes prevent the shell from "interpreting" or expanding all special characters. Often single quotes are used to protect a string (a sequence of characters) from being changed by the shell, so that the string can be interpreted by a command as a parameter to affect the way the command is executed. Double " quotes stop the expansion of glob characters like the asterisk (*), question mark (?), and square brackets ( [] ). Double quotes do allow for both variable expansion and command substitution (see back quotes) to take place. Back ` quotes cause command substitution which allows for a command to be executed within the line of another command. When using quotes, they must be entered in pairs or else the shell will not consider the command complete. While single quotes are useful for blocking the shell from interpreting one or more characters, the shell also provides a way to block the interpretation of just a single character called "escaping" the character. To escape the special meaning of a shell metacharacter, the backslash \ character is used as a prefix to that one character.

5.6.3 Backslash Character

There is also an alternative technique to essentially single quote a single character. Consider the following message: The service costs $1 and the path is $PATH If this sentence is placed in double quotes, $1 and $PATH are considered variables. sysadmin@localhost:~$ echo "The service costs $1 and the path is $PATH" ‌⁠​​⁠​The service costs and the path is /usr/bin/custom:/home/sysadmin/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games If it is placed in single quotes, $1 and $PATH are not considered variables. sysadmin@localhost:~$ echo 'The service costs $1 and the path is $PATH' The service costs $1 and the path is $PATH But what if you want to have $PATH treated as a variable and $1 not? In this case, use a backslash \ character in front of the dollar sign $ character to prevent the shell from interpreting it. The command below demonstrates using the \ character: sysadmin@localhost:~$ echo The service costs \$1 and the path is $PATH The service costs $1 and the path is /usr/bin/custom:/home/sysadmin/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games

5.3.3 Step 3

To execute a command again, type the exclamation point and the history list number. For example, to execute the 9th command in your history list, you would execute the following: !9 sysadmin@localhost:~$ !9 echo Hi Hi

5.3.2 Step 2

To view a limited number of commands, the history command can take a number as a parameter to display exactly that many recent entries. Type the following command to display the last five commands from your history: history 5 Your output should be similar to the following: sysadmin@localhost:~$ history 5 7 uname --nodename 8 pwd 9 echo Hi 10 history 11 history 5

5.4.3 Step 3

Type the following command to display the value of the PATH variable: echo $PATH Your output should be similar to the following: sysadmin@localhost:~$ echo $PATH /home/sysadmin/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games sysadmin@localhost:~$ The PATH variable is displayed by placing a $ character in front of the name of the variable. This variable is used to find the location of commands. Each of the directories listed above are searched when you run a command. For example, if you try to run the date command, the shell will first look for the command in the /home/sysadmin/bin directory and then in the /usr/local/sbin directory and so on. Once the date command is found, the shell "runs it".

5.7 Control Statements

Typically, you type a single command and you execute it when you press Enter. The Bash shell offers three different statements that can be used to separate multiple commands typed together. The simplest separator is the semicolon (;). Using the semicolon between multiple commands allows for them to be executed one right after another, sequentially from left to right. The && characters create a logical "and" statement. Commands separated by && are conditionally executed. If the command on the left of the && is successful, then the command to the right of the && will also be executed. If the command to the left of the && fails, then the command to the right of the && is not executed. The || characters create a logical "or" statement, which also causes conditional execution. When commands are separated by ||, then only if the command to the left fails, does the command to the right of the || execute. If the command to the left of the || succeeds, then the command to the right of the || will not execute. To see how these control statements work, you will be using two special executables: true and false. The true executable always succeeds when it executes, whereas, the false executable always fails. While this may not provide you with realistic examples of how && and || work, it does provide a means to demonstrate how they work without having to introduce new commands.

5.7.4 Step 4

Use logical "and" with a command that fails as shown below: echo Success && false && echo Bye Your output should be similar to the following: sysadmin@localhost:~$ echo Success && false && echo Bye Success sysadmin@localhost:~$ The first echo command succeeds and we see its output. The false command executes with a failure result, so the last echo statement is not executed.

5.4.4 Step 4

Use the which command to determine if there is an executable file, in this case named date, that is located within a directory listed in the PATH value: which date Your output should be similar to the following: sysadmin@localhost:~$ which date /bin/date sysadmin@localhost:~$ The output of the which command tells you that when you execute the date command, the system will run the command /bin/date. The which command makes use of the PATH variable to determine the location of the date command.

Variables

Used to store information for the Bash shell and for the user. These variables can be used to modify how commands and features work as well as provide vital system information.

PATH environment variable

Variable containing a list that defines which directories the shell looks in for commands.

5.3 Commands

What is a command? The simplest answer is that a command is a software program that, when executed on the CLI, performs an action on the computer. To execute a command, the first step is to type the name of the command. Click in the terminal on the right. Type ls and hit Enter. The result should resemble the example below: sysadmin@localhost:~$ ls Desktop Documents Downloads Music Pictures Public Templates Videos Note: By itself, the ls command lists files and directories contained in the current working directory. At this point, you shouldn't worry too much about the output of the command, instead, focus on understanding how to format and execute commands. The ls command will be covered in complete detail later in the course. Many commands can be used by themselves with no further input. Some commands require additional input to run correctly. This additional input comes in two forms: options and arguments. The typical format for a command is as follows: command [options] [arguments] Options are used to modify the core behavior of a command while arguments are used to provide additional information (such as a filename or a username). Each option and argument is normally separated by a space, although options can often be combined. Keep in mind that Linux is case-sensitive. Commands, options, arguments, variables, and file names must be entered exactly as shown.

5.3.3 History

When a command is executed in the terminal, it is stored in a history list. This is designed to make it easy to execute the same command, later eliminating the need to retype the entire command. Pressing the Up Arrow ↑ key displays the previous command on the prompt line. The entire history of commands run in the current session can be displayed by pressing Up repeatedly to move back through the history of commands that have been run. Pressing the Enter key runs the displayed command again. When the desired command is located, the Left Arrow ← and Right Arrow → keys can position the cursor for editing. Other useful keys for editing include the Home, End, Backspace and Delete keys. To view the history list of a terminal, use the history command: sysadmin@localhost:~$ date Wed Dec 12 04:28:12 UTC 2018 sysadmin@localhost:~$ ls Desktop Documents Downloads Music Pictures Public Templates Videos sysadmin@localhost:~$ cal 5 2030 May 2030 Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 sysadmin@localhost:~$ history 1 date 2 ls 3 cal 5 2030 4 history If the desired command is in the list that the history command generates, it can be executed by typing an exclamation point ! character and then the number next to the command, for example, to execute the cal command again: sysadmin@localhost:~$ history 1 date 2 ls 3 cal 5 2030 4 history sysadmin@localhost:~$ !3 cal 5 2030 May 2030 Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 If the history command is passed a number as an argument, it outputs that number of previous commands from the history list. For example, to show the last three commands: sysadmin@localhost:~$ history 3 6 date 7 ls /home 8 history 3 ‌⁠​​⁠​ To execute the nth command from the bottom of the history list, type !-n and hit Enter. For example, to execute the third command from the bottom of the history list execute the following: sysadmin@localhost:~$ !-3 date Wed Dec 12 04:31:55 UTC 2018 To execute the most recent command type !! and hit Enter: sysadmin@localhost:~$ date Wed Dec 12 04:32:36 UTC 2018 sysadmin@localhost:~$ !! date Wed Dec 12 04:32:38 UTC 2018 To execute the most recent iteration of a specific command, type ! followed by the name of the command and hit Enter. For example, to execute the most recent ls command: sysadmin@localhost:~$ !ls ls /home sysadmin

5.6.2 Step 2

You can also place $( before the command and ) after the command to accomplish command substitution: echo Today is $(date) Your output should be similar to the following: sysadmin@localhost:~$ echo Today is $(date) Today is Mon Dec 3 21:33:41 UTC 2018 Why two different methods that accomplish the same thing? Backquotes look very similar to single quotes, making it harder to "see" what a command is supposed to do. Originally, shells used backquotes; the $(command) format was added in a later version of the Bash shell to make the statement more visually clear.

5.3.1 Arguments

command [options] [arguments] An argument can be used to specify something for the command to act upon. If the ls command is given the name of a directory as an argument, it lists the contents of that directory. In the following example, the /etc/ppp directory is used as an argument; the resulting output is a list of files contained in that directory: sysadmin@localhost:~$ ls /etc/ppp ip-down.d ip-up.d The ls command also accepts multiple arguments. To list the contents of both the /etc/ppp and /etc/ssh directories, pass them both as arguments: sysadmin@localhost:~$ ls /etc/ppp /etc/ssh /etc/ppp: ip-down.d ip-up.d /etc/ssh: moduli ssh_host_dsa_key.pub ssh_host_rsa_key sshd_configssh_config ssh_host_ecdsa_key ssh_host_rsa_key.pub ssh_host_dsa_key ssh_host_ecdsa_key.pub ssh_import_id

5.3.2 Options

command [options] [arguments] Options can be used with commands to expand or modify the way a command behaves. For example, using the -l option of the ls command results in a long listing, providing additional information about the files that are listed, such as the permissions, the size of the file and other information: sysadmin@localhost:~$ ls -l total 0 drwxr-xr-x 1 sysadmin sysadmin 0 Jan 29 20:13 Desktop drwxr-xr-x 1 sysadmin sysadmin 0 Jan 29 20:13 Documents drwxr-xr-x 1 sysadmin sysadmin 0 Jan 29 20:13 Downloads drwxr-xr-x 1 sysadmin sysadmin 0 Jan 29 20:13 Music drwxr-xr-x 1 sysadmin sysadmin 0 Jan 29 20:13 Pictures drwxr-xr-x 1 sysadmin sysadmin 0 Jan 29 20:13 Public drwxr-xr-x 1 sysadmin sysadmin 0 Jan 29 20:13 Templates drwxr-xr-x 1 sysadmin sysadmin 0 Jan 29 20:13 Videos Note that, in the command above, -l is a lowercase letter "L". An easy way to remember this is -l is a mnemonic (easy to memorize programming code) for long listing). Often the character is chosen to be mnemonic for its purpose, like choosing the letter l for long or r for reverse. By default, the ls command prints the results in alphabetical order, and so by adding the -r option, it prints the results in reverse alphabetical order. sysadmin@localhost:~$ ls -r Videos Templates Public Pictures Music Downloads Documents Desktop In most cases, options can be used in conjunction with other options. They can be given as separate options, as in -l -r, or combined, as in -lr. The combination of these two options would result in a long listing output in reverse alphabetical order: sysadmin@localhost:~$ ls -lr total 32 drwxr-xr-x 2 sysadmin sysadmin 4096 Oct 31 20:13 Videos drwxr-xr-x 2 sysadmin sysadmin 4096 Oct 31 20:13 Templates drwxr-xr-x 2 sysadmin sysadmin 4096 Oct 31 20:13 Public drwxr-xr-x 2 sysadmin sysadmin 4096 Oct 31 20:13 Pictures drwxr-xr-x 2 sysadmin sysadmin 4096 Oct 31 20:13 Music drwxr-xr-x 2 sysadmin sysadmin 4096 Oct 31 20:13 Downloads drwxr-xr-x 4 sysadmin sysadmin 4096 Oct 31 20:13 Documents drwxr-xr-x 2 sysadmin sysadmin 4096 Oct 31 20:13 Desktop The order of the combined options isn't important. The output of all of these examples would be the same: ls -l -r ls -rl ls -lr By default the -l option of the ls command displays files sizes in bytes: sysadmin@localhost:~$ ls -l /usr/bin/perl -rwxr-xr-x 2 root root 10376 Feb 4 2018 /usr/bin/perl If the -h option is added the file sizes will be displayed in human-readable format: sysadmin@localhost:~$ ls -lh /usr/bin/perl -rwxr-xr-x 2 root root 11K Feb 4 2018 /usr/bin/perl Options are often single letters; however, sometimes they are words or phrases as well. Typically, older commands use single letters while newer commands use complete words for options. Single-letter options are preceded by a single dash - character, like the -h option. Full-word options are preceded by two dash -- characters. The -h option also has an equivalent full-word form; the --human-readable option. sysadmin@localhost:~$ ls -l --human-readable /usr/bin/perl -rwxr-xr-x 2 root root 11K Feb 4 2018 /usr/bin/perl

5.7.2 Double Ampersand

command1 && command2 The double ampersand && acts as a logical "and"; if the first command is successful, then the second command will also run. If the first command fails, then the second command will not run. To better understand how this works, consider first the concept of failure and success for commands. Commands succeed when they work properly and fail when something goes wrong. For example, consider the ls command. The command succeeds if the given directory is accessible and fails if it isn't. In the following example, the first command succeeds because the /etc/ppp directory exists and is accessible while the second command fails because there is no /junk directory: sysadmin@localhost:~$ ls /etc/ppp ip-down.d ip-up.d sysadmin@localhost:~$ ls /etc/junk ls: cannot access /etc/junk: No such file or directory To use the success or failure of the ls command in conjunction with && execute commands like the following. In the first example, the echo command is executed because the ls command succeeds: sysadmin@localhost:~$ ls /etc/ppp && echo success ip-down.d ip-up.d success In the second example, the echo command isn't executed because the ls command fails: sysadmin@localhost:~$ ls /etc/junk && echo success ls: cannot access /etc/junk: No such file or directory

5.7.3 Double Pipe

command1 || command2 The double pipe || is a logical "or". Depending on the result of the first command, the second command will either run or be skipped. With the double pipe, if the first command runs successfully, the second command is skipped; if the first command fails, then the second command is run. In other words, you are essentially telling the shell, "Either run this first command or the second one". In the following example, the echo command only executes if the ls command fails: sysadmin@localhost:~$ ls /etc/ppp || echo failed ip-down.d ip-up.d sysadmin@localhost:~$ ls /etc/junk || echo failed ls: cannot access /etc/junk: No such file or directory failed

5.7.1 Semicolon

command1; command2; command3 The semicolon ; character can be used to run multiple commands, one after the other. Each command runs independently and consecutively; regardless of the result of the first command, the second command runs once the first has completed, then the third and so on. For example, to print the months of January, February and March of 2030, execute the following command: sysadmin@localhost:~$ cal 1 2030; cal 2 2030; cal 3 2030 January 2030 Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 February 2030 Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 March 2030 Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

System Name:

localhost in sysadmin@localhost:~$

User Name:

sysadmin in sysadmin@localhost:~$

Common Prompt Structure

sysadmin@localhost:~$

Current Directory:

~ in sysadmin@localhost:~$


Set pelajaran terkait

Woo & Robinson- Pharm Ch. 14 & 17 Respiratory and GI

View Set

NUR 2144 Pharmacology II Chapter 49: Drugs Used to Treat Anemias

View Set

Institute Q's Alternative Investments

View Set

Pediatrics Exam 2 - HAVE NOT REVIEWED YET

View Set