The Linux Command Line 2nd Edition

This book is for new Linux users who have migrated from other platforms.


William E. Shotts, Jr.


538 Pages

31430 Reads

40 Downloads

English

PDF Format

1.85 MB

Other Books

Download PDF format


  • William E. Shotts, Jr.   
  • 538 Pages   
  • 22 Feb 2015
  • Page - 1

    read more..

  • Page - 2

    read more..

  • Page - 3

    read more..

  • Page - 4

    read more..

  • Page - 5

    read more..

  • Page - 6

    read more..

  • Page - 7

    read more..

  • Page - 8

    read more..

  • Page - 9

    read more..

  • Page - 10

    read more..

  • Page - 11

    read more..

  • Page - 12

    read more..

  • Page - 13

    read more..

  • Page - 14

    read more..

  • Page - 15

    read more..

  • Page - 16

    read more..

  • Page - 17

    read more..

  • Page - 18

    read more..

  • Page - 19

    read more..

  • Page - 20

    read more..

  • Page - 21

    read more..

  • Page - 22

    read more..

  • Page - 23

    read more..

  • Page - 24

    read more..

  • Page - 25

    read more..

  • Page - 26

    read more..

  • Page - 27

    read more..

  • Page - 28

    read more..

  • Page - 29

    read more..

  • Page - 30

    read more..

  • Page - 31

    read more..

  • Page - 32

    read more..

  • Page - 33

    read more..

  • Page - 34

    read more..

  • Page - 35

    read more..

  • Page - 36

    read more..

  • Page - 37

    read more..

  • Page - 38

    read more..

  • Page - 39

    read more..

  • Page - 40

    More Fun With ls We'll add the long option “--reverse” to reverse the order of the sort: [me@linuxbox ~]$ ls -lt --reverse Note that command options, like filenames in Linux, are case-sensitive. The ls command has a large number of possible options. The most common are listed in Table 3-1. Table 3- 1: Common ls read more..

  • Page - 41

    3 – Exploring The System A Longer Look At Long Format As we saw before, the “-l” option causes ls to display its results in long format. This for- mat contains a great deal of useful information. Here is the Examples directory from an Ubuntu system: -rw-r--r-- 1 root root 3576296 2007-04-03 11:05 Experience ubuntu.ogg read more..

  • Page - 42

    Determining A File's Type With file Determining A File's Type With file As we explore the system it will be useful to know what files contain. To do this we will use the file command to determine a file's type. As we discussed earlier, filenames in Linux are not required to reflect a file's read more..

  • Page - 43

    3 – Exploring The System Code for Information Interchange. This is a simple encoding scheme that was first used on Teletype machines to map keyboard characters to numbers. Text is a simple one-to-one mapping of characters to numbers. It is very compact. Fifty characters of text translates to fifty bytes of data. read more..

  • Page - 44

    Viewing File Contents With less Table 3-3: less Commands Command Action Page Up or b Scroll back one page Page Down or space Scroll forward one page Up Arrow Scroll up one line Down Arrow Scroll down one line G Move to the end of the text file 1G or g Move to the beginning of the text file /characters Search forward to the next read more..

  • Page - 45

    3 – Exploring The System 1. cd into a given directory 2. List the directory contents with ls -l 3. If you see an interesting file, determine its contents with file 4. If it looks like it might be text, try viewing it with less Remember the copy and paste trick! If you are using a mouse, you can double read more..

  • Page - 46

    A Guided Tour Directory Comments /etc The /etc directory contains all of the system-wide configuration files. It also contains a collection of shell scripts which start each of the system services at boot time. Everything in this directory should be readable text. Interesting files: While everything in /etc is interesting, here are read more..

  • Page - 47

    3 – Exploring The System Directory Comments /proc The /proc directory is special. It's not a real file system in the sense of files stored on your hard drive. Rather, it is a virtual file system maintained by the Linux kernel. The “files” it contains are peepholes into the kernel itself. The files are readable read more..

  • Page - 48

    A Guided Tour Directory Comments /var With the exception of /tmp and /home, the directories we have looked at so far remain relatively static, that is, their contents don't change. The /var directory tree is where data that is likely to change is stored. Various databases, spool files, user mail, etc. are located here. read more..

  • Page - 49

    3 – Exploring The System symbolic link pointing to the old version. The directory listing above (from the /lib directory of a Fedora system) shows a sym- bolic link called “libc.so.6” that points to a shared library file called “libc-2.6.so.” This means that programs looking for “libc.so.6” will actually read more..

  • Page - 50

    4 – Manipulating Files And Directories 4 – Manipulating Files And Directories At this point, we are ready for some real work! This chapter will introduce the following commands: ● cp – Copy files and directories ● mv – Move/rename files and directories ● mkdir – Create directories ● rm – Remove files and directories read more..

  • Page - 51

    4 – Manipulating Files And Directories called wildcards. Using wildcards (which is also known as globbing) allow you to select filenames based on patterns of characters. The table below lists the wildcards and what they select: Table 4-1: Wildcards Wildcard Meaning * Matches any characters ? Matches any single character [characters] read more..

  • Page - 52

    Wildcards Data??? Any file beginning with “Data” followed by exactly three characters [abc]* Any file beginning with either an “a”, a “b”, or a “c” BACKUP.[0-9][0-9][0-9] Any file beginning with “BACKUP.” followed by exactly three numerals [[:upper:]]* Any file beginning with an uppercase letter [![:digit:]]* Any file not beginning with a read more..

  • Page - 53

    4 – Manipulating Files And Directories Many ideas originally found in the command line interface make their way into the graphical interface, too. It is one of the many things that make the Linux desk- top so powerful. mkdir – Create Directories The mkdir command is used to create directories. It works like this: read more..

  • Page - 54

    cp – Copy Files And Directories Useful Options And Examples Here are some of the commonly used options (the short option and the equivalent long option) for cp: Table 4-4: cp Options Option Meaning -a, --archive Copy the files and directories and all of their attributes, including ownerships and permissions. Normally, copies take on read more..

  • Page - 55

    4 – Manipulating Files And Directories cp -r dir1 dir2 Copy the contents of directory dir1 to directory dir2. If directory dir2 does not exist, it is created and, after the copy, will contain the same contents as directory dir1. If directory dir2 does exist, then directory dir1 (and its contents) will be copied into read more..

  • Page - 56

    mv – Move And Rename Files performed. Table 4-7: mv Examples Command Results mv file1 file2 Move file1 to file2. If file2 exists, it is overwritten with the contents of file1. If file2 does not exist, it is created. In either case, file1 ceases to exist. mv -i file1 file2 Same as above, except that if file2 exists, the read more..

  • Page - 57

    4 – Manipulating Files And Directories -r, --recursive Recursively delete directories. This means that if a directory being deleted has subdirectories, delete them too. To delete a directory, this option must be specified. -f, --force Ignore nonexistent files and do not prompt. This overrides the --interactive option. -v, --verbose Display read more..

  • Page - 58

    rm – Remove Files And Directories files that will be deleted. Then press the up arrow key to recall the command and replace the ls with rm. ln – Create Links The ln command is used to create either hard or symbolic links. It is used in one of two ways: ln file link to create a hard link, read more..

  • Page - 59

    4 – Manipulating Files And Directories directory. In this regard, they operate in much the same way as a Windows shortcut though of course, they predate the Windows feature by many years ;-) A file pointed to by a symbolic link, and the symbolic link itself are largely indistinguish- able from one another. read more..

  • Page - 60

    Let's Build A Playground cp command, we'll copy the passwd file from the /etc directory to the current work- ing directory: [me@linuxbox playground]$ cp /etc/passwd . Notice how we used the shorthand for the current working directory, the single trailing period. So now if we perform an ls, we will see our file: read more..

  • Page - 61

    4 – Manipulating Files And Directories Let's pass the fun around a little by moving our renamed file to each of the directories and back again: [me@linuxbox playground]$ mv fun dir1 to move it first to directory dir1, then: [me@linuxbox playground]$ mv dir1/fun dir2 to move it from dir1 to dir2, then: [me@linuxbox playground]$ mv read more..

  • Page - 62

    Let's Build A Playground Creating Hard Links Now we'll try some links. First the hard links. We’ll create some links to our data file like so: [me@linuxbox playground]$ ln fun fun-hard [me@linuxbox playground]$ ln fun dir1/fun-hard [me@linuxbox playground]$ ln fun dir2/fun-hard So now we have four instances of the file “fun”. Let's read more..

  • Page - 63

    4 – Manipulating Files And Directories 12353538 -rw-r--r-- 4 me me 1650 2008-01-10 16:33 fun-hard In this version of the listing, the first field is the inode number and, as we can see, both fun and fun-hard share the same inode number, which confirms they are the same file. Creating Symbolic Links Symbolic read more..

  • Page - 64

    Let's Build A Playground or relative pathnames, as we did in our earlier example. Using relative pathnames is more desirable because it allows a directory containing symbolic links to be renamed and/or moved without breaking the links. In addition to regular files, symbolic links can also reference directories: [me@linuxbox read more..

  • Page - 65

    4 – Manipulating Files And Directories [me@linuxbox playground]$ ls -l total 8 drwxrwxr-x 2 me me 4096 2008-01-15 15:17 dir1 lrwxrwxrwx 1 me me 4 2008-01-16 14:45 dir1-sym -> dir1 drwxrwxr-x 2 me me 4096 2008-01-15 15:17 dir2 lrwxrwxrwx 1 me me 3 2008-01-15 15:15 fun-sym -> fun Most Linux distributions configure ls read more..

  • Page - 66

    Let's Build A Playground while dragging a file will create a link rather than copying (or moving) the file. In KDE, a small menu appears whenever a file is dropped, offering a choice of copy- ing, moving, or linking the file. Summing Up We've covered a lot of ground here and it will take a while to read more..

  • Page - 67

    5 – Working With Commands 5 – Working With Commands Up to this point, we have seen a series of mysterious commands, each with its own mys- terious options and arguments. In this chapter, we will attempt to remove some of that mystery and even create some of our own commands. The commands introduced read more..

  • Page - 68

    Identifying Commands Identifying Commands It is often useful to know exactly which of the four kinds of commands is being used and Linux provides a couple of ways to find out. type – Display A Command's Type The type command is a shell builtin that displays the kind of command the shell will execute, read more..

  • Page - 69

    5 – Working With Commands [me@linuxbox ~]$ which cd /usr/bin/which: no cd in (/opt/jre1.6.0_03/bin:/usr/lib/qt- 3.3/bin:/usr/kerberos/bin:/opt/jre1.6.0_03/bin:/usr/lib/ccache:/usr/l ocal/bin:/usr/bin:/bin:/home/me/bin) which is a fancy way of saying “command not found.” Getting A Command's Documentation With this knowledge of what a command is, we can now search for the read more..

  • Page - 70

    Getting A Command's Documentation A note on notation: When square brackets appear in the description of a command's syn- tax, they indicate optional items. A vertical bar character indicates mutually exclusive items. In the case of the cd command above: cd [-L|[-P[-e]]] [dir] This notation says that the command cd may read more..

  • Page - 71

    5 – Working With Commands man program where “program” is the name of the command to view. Man pages vary somewhat in format but generally contain a title, a synopsis of the com- mand's syntax, a description of the command's purpose, and a listing and description of each of the command's options. Man pages, read more..

  • Page - 72

    Getting A Command's Documentation man section search_term For example: [me@linuxbox ~]$ man 5 passwd This will display the man page describing the file format of the /etc/passwd file. apropos – Display Appropriate Commands It is also possible to search the list of man pages for possible matches based on a search term. It's read more..

  • Page - 73

    5 – Working With Commands The Most Brutal Man Page Of Them All As we have seen, the manual pages supplied with Linux and other Unix-like sys- tems are intended as reference documentation and not as tutorials. Many man pages are hard to read, but I think that the grand prize for difficulty has got read more..

  • Page - 74

    Getting A Command's Documentation By default, the output is sorted alphabetically, according to the --zz-Info: (coreutils.info.gz)ls invocation, 63 lines --Top---------- The info program reads info files, which are tree structured into individual nodes, each containing a single topic. Info files contain hyperlinks that can move you from read more..

  • Page - 75

    5 – Working With Commands be viewed with less. Some of the files are in HTML format and can be viewed with a web browser. We may encounter some files ending with a “.gz” extension. This indicates that they have been compressed with the gzip compression program. The gzip package includes a read more..

  • Page - 76

    Creating Your Own Commands With alias Great! “foo” is not taken. So let's create our alias: [me@linuxbox ~]$ alias foo='cd /usr; ls; cd -' Notice the structure of this command: alias name='string' After the command “alias” we give alias a name followed immediately (no whitespace al- lowed) by an equals sign, followed immediately by read more..

  • Page - 77

    5 – Working With Commands [me@linuxbox ~]$ type ls ls is aliased to `ls --color=tty' To see all the aliases defined in the environment, use the alias command without argu- ments. Here are some of the aliases defined by default on a Fedora system. Try and figure out what they all do: [me@linuxbox ~]$ alias alias l.='ls -d .* read more..

  • Page - 78

    6 – Redirection 6 – Redirection In this lesson we are going to unleash what may be the coolest feature of the command line. It's called I/O redirection. The “I/O” stands for input/output and with this facility you can redirect the input and output of commands to and from files, as well as read more..

  • Page - 79

    6 – Redirection I/O redirection allows us to change where output goes and where input comes from. Nor- mally, output goes to the screen and input comes from the keyboard, but with I/O redi- rection, we can change that. Redirecting Standard Output I/O redirection allows us to redefine where standard output goes. read more..

  • Page - 80

    Redirecting Standard Output to redirect standard error in just a minute, but first, let's look at what happened to our out- put file: [me@linuxbox ~]$ ls -l ls-output.txt -rw-rw-r-- 1 me me 0 2008-02-01 15:08 ls-output.txt The file now has zero length! This is because, when we redirect output with the “>” redi- read more..

  • Page - 81

    6 – Redirection standard error we must refer to its file descriptor. A program can produce output on any of several numbered file streams. While we have referred to the first three of these file streams as standard input, output and error, the shell references them internally as file de- scriptors 0, read more..

  • Page - 82

    Redirecting Standard Error combined redirection: [me@linuxbox ~]$ ls -l /bin/usr &> ls-output.txt In this example, we use the single notation &> to redirect both standard output and stan- dard error to the file ls-output.txt. You may also append the standard output and standard error streams to a single file like read more..

  • Page - 83

    6 – Redirection cat [file...] In most cases, you can think of cat as being analogous to the TYPE command in DOS. You can use it to display files without paging, for example: [me@linuxbox ~]$ cat ls-output.txt will display the contents of the file ls-output.txt. cat is often used to display short text files. Since read more..

  • Page - 84

    Redirecting Standard Input reached end of file (EOF) on standard input: [me@linuxbox ~]$ cat The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. In the absence of filename arguments, cat copies standard input to standard output, so we see our line of text repeated. We can use this behavior read more..

  • Page - 85

    6 – Redirection utilized by a shell feature called pipelines. Using the pipe operator “|” (vertical bar), the standard output of one command can be piped into the standard input of another: command1 | command2 To fully demonstrate this, we are going to need some commands. Remember how we said there was one we read more..

  • Page - 86

    Pipelines The first command put him in the directory where most programs are stored and the second command told the shell to overwrite the file less with the output of the ls command. Since the /usr/bin directory already contained a file named “less” (the less program), the second command overwrote read more..

  • Page - 87

    6 – Redirection [me@linuxbox ~]$ ls /bin /usr/bin | sort | uniq -d | less wc – Print Line, Word, And Byte Counts The wc (word count) command is used to display the number of lines, words, and bytes contained in files. For example: [me@linuxbox ~]$ wc ls-output.txt 7902 64566 503634 ls-output.txt In this case it prints out read more..

  • Page - 88

    Pipelines bunzip2 bzip2 gunzip gzip unzip zip zipcloak zipgrep zipinfo zipnote zipsplit There are a couple of handy options for grep: “-i” which causes grep to ignore case when performing the search (normally searches are case sensitive) and “-v” which tells grep to only print lines that do not match the pattern. head / read more..

  • Page - 89

    6 – Redirection zsoelim tail has an option which allows you to view files in real-time. This is useful for watch- ing the progress of log files as they are being written. In the following example, we will look at the messages file in /var/log (or the /var/log/syslog file if mes- sages is missing). read more..

  • Page - 90

    read more..

  • Page - 91

    read more..

  • Page - 92

    read more..

  • Page - 93

    read more..

  • Page - 94

    read more..

  • Page - 95

    read more..

  • Page - 96

    read more..

  • Page - 97

    read more..

  • Page - 98

    read more..

  • Page - 99

    read more..

  • Page - 100

    read more..

  • Page - 101

    read more..

  • Page - 102

    read more..

  • Page - 103

    read more..

  • Page - 104

    read more..

  • Page - 105

    read more..

  • Page - 106

    read more..

  • Page - 107

    read more..

  • Page - 108

    read more..

  • Page - 109

    read more..

  • Page - 110

    read more..

  • Page - 111

    read more..

  • Page - 112

    read more..

  • Page - 113

    read more..

  • Page - 114

    read more..

  • Page - 115

    read more..

  • Page - 116

    read more..

  • Page - 117

    read more..

  • Page - 118

    read more..

  • Page - 119

    read more..

  • Page - 120

    read more..

  • Page - 121

    read more..

  • Page - 122

    read more..

  • Page - 123

    read more..

  • Page - 124

    read more..

  • Page - 125

    read more..

  • Page - 126

    read more..

  • Page - 127

    read more..

  • Page - 128

    read more..

  • Page - 129

    read more..

  • Page - 130

    read more..

  • Page - 131

    read more..

  • Page - 132

    read more..

  • Page - 133

    read more..

  • Page - 134

    read more..

  • Page - 135

    read more..

  • Page - 136

    read more..

  • Page - 137

    read more..

  • Page - 138

    read more..

  • Page - 139

    read more..

  • Page - 140

    read more..

  • Page - 141

    read more..

  • Page - 142

    read more..

  • Page - 143

    read more..

  • Page - 144

    read more..

  • Page - 145

    read more..

  • Page - 146

    read more..

  • Page - 147

    read more..

  • Page - 148

    read more..

  • Page - 149

    read more..

  • Page - 150

    read more..

  • Page - 151

    read more..

  • Page - 152

    read more..

  • Page - 153

    read more..

  • Page - 154

    read more..

  • Page - 155

    read more..

  • Page - 156

    read more..

  • Page - 157

    read more..

  • Page - 158

    read more..

  • Page - 159

    read more..

  • Page - 160

    read more..

  • Page - 161

    read more..

  • Page - 162

    read more..

  • Page - 163

    read more..

  • Page - 164

    read more..

  • Page - 165

    read more..

  • Page - 166

    read more..

  • Page - 167

    read more..

  • Page - 168

    read more..

  • Page - 169

    read more..

  • Page - 170

    read more..

  • Page - 171

    read more..

  • Page - 172

    read more..

  • Page - 173

    read more..

  • Page - 174

    read more..

  • Page - 175

    read more..

  • Page - 176

    read more..

  • Page - 177

    read more..

  • Page - 178

    read more..

  • Page - 179

    read more..

  • Page - 180

    read more..

  • Page - 181

    read more..

  • Page - 182

    read more..

  • Page - 183

    read more..

  • Page - 184

    read more..

  • Page - 185

    read more..

  • Page - 186

    read more..

  • Page - 187

    read more..

  • Page - 188

    read more..

  • Page - 189

    read more..

  • Page - 190

    read more..

  • Page - 191

    read more..

  • Page - 192

    read more..

  • Page - 193

    read more..

  • Page - 194

    read more..

  • Page - 195

    read more..

  • Page - 196

    read more..

  • Page - 197

    read more..

  • Page - 198

    read more..

  • Page - 199

    read more..

  • Page - 200

    read more..

  • Page - 201

    read more..

  • Page - 202

    read more..

  • Page - 203

    read more..

  • Page - 204

    read more..

  • Page - 205

    read more..

  • Page - 206

    read more..

  • Page - 207

    read more..

  • Page - 208

    read more..

  • Page - 209

    read more..

  • Page - 210

    read more..

  • Page - 211

    read more..

  • Page - 212

    read more..

  • Page - 213

    read more..

  • Page - 214

    read more..

  • Page - 215

    read more..

  • Page - 216

    read more..

  • Page - 217

    read more..

  • Page - 218

    read more..

  • Page - 219

    read more..

  • Page - 220

    read more..

  • Page - 221

    read more..

  • Page - 222

    read more..

  • Page - 223

    read more..

  • Page - 224

    read more..

  • Page - 225

    read more..

  • Page - 226

    read more..

  • Page - 227

    read more..

  • Page - 228

    read more..

  • Page - 229

    read more..

  • Page - 230

    read more..

  • Page - 231

    read more..

  • Page - 232

    read more..

  • Page - 233

    read more..

  • Page - 234

    read more..

  • Page - 235

    read more..

  • Page - 236

    read more..

  • Page - 237

    read more..

  • Page - 238

    read more..

  • Page - 239

    read more..

  • Page - 240

    read more..

  • Page - 241

    read more..

  • Page - 242

    read more..

  • Page - 243

    read more..

  • Page - 244

    read more..

  • Page - 245

    read more..

  • Page - 246

    read more..

  • Page - 247

    read more..

  • Page - 248

    read more..

  • Page - 249

    read more..

  • Page - 250

    read more..

  • Page - 251

    read more..

  • Page - 252

    read more..

  • Page - 253

    read more..

  • Page - 254

    read more..

  • Page - 255

    read more..

  • Page - 256

    read more..

  • Page - 257

    read more..

  • Page - 258

    read more..

  • Page - 259

    read more..

  • Page - 260

    read more..

  • Page - 261

    read more..

  • Page - 262

    read more..

  • Page - 263

    read more..

  • Page - 264

    read more..

  • Page - 265

    read more..

  • Page - 266

    read more..

  • Page - 267

    read more..

  • Page - 268

    read more..

  • Page - 269

    read more..

  • Page - 270

    read more..

  • Page - 271

    read more..

  • Page - 272

    read more..

  • Page - 273

    read more..

  • Page - 274

    read more..

  • Page - 275

    read more..

  • Page - 276

    read more..

  • Page - 277

    read more..

  • Page - 278

    read more..

  • Page - 279

    read more..

  • Page - 280

    read more..

  • Page - 281

    read more..

  • Page - 282

    read more..

  • Page - 283

    read more..

  • Page - 284

    read more..

  • Page - 285

    read more..

  • Page - 286

    read more..

  • Page - 287

    read more..

  • Page - 288

    read more..

  • Page - 289

    read more..

  • Page - 290

    read more..

  • Page - 291

    read more..

  • Page - 292

    read more..

  • Page - 293

    read more..

  • Page - 294

    read more..

  • Page - 295

    read more..

  • Page - 296

    read more..

  • Page - 297

    read more..

  • Page - 298

    read more..

  • Page - 299

    read more..

  • Page - 300

    read more..

  • Page - 301

    read more..

  • Page - 302

    read more..

  • Page - 303

    read more..

  • Page - 304

    read more..

  • Page - 305

    read more..

  • Page - 306

    read more..

  • Page - 307

    read more..

  • Page - 308

    read more..

  • Page - 309

    read more..

  • Page - 310

    read more..

  • Page - 311

    read more..

  • Page - 312

    read more..

  • Page - 313

    read more..

  • Page - 314

    read more..

  • Page - 315

    read more..

  • Page - 316

    read more..

  • Page - 317

    read more..

  • Page - 318

    read more..

  • Page - 319

    read more..

  • Page - 320

    read more..

  • Page - 321

    read more..

  • Page - 322

    read more..

  • Page - 323

    read more..

  • Page - 324

    read more..

  • Page - 325

    read more..

  • Page - 326

    read more..

  • Page - 327

    read more..

  • Page - 328

    read more..

  • Page - 329

    read more..

  • Page - 330

    read more..

  • Page - 331

    read more..

  • Page - 332

    read more..

  • Page - 333

    read more..

  • Page - 334

    read more..

  • Page - 335

    read more..

  • Page - 336

    read more..

  • Page - 337

    read more..

  • Page - 338

    read more..

  • Page - 339

    read more..

  • Page - 340

    read more..

  • Page - 341

    read more..

  • Page - 342

    read more..

  • Page - 343

    read more..

  • Page - 344

    read more..

  • Page - 345

    read more..

  • Page - 346

    read more..

  • Page - 347

    read more..

  • Page - 348

    read more..

  • Page - 349

    read more..

  • Page - 350

    read more..

  • Page - 351

    read more..

  • Page - 352

    read more..

  • Page - 353

    read more..

  • Page - 354

    read more..

  • Page - 355

    read more..

  • Page - 356

    read more..

  • Page - 357

    read more..

  • Page - 358

    read more..

  • Page - 359

    read more..

  • Page - 360

    read more..

  • Page - 361

    read more..

  • Page - 362

    read more..

  • Page - 363

    read more..

  • Page - 364

    read more..

  • Page - 365

    read more..

  • Page - 366

    read more..

  • Page - 367

    read more..

  • Page - 368

    read more..

  • Page - 369

    read more..

  • Page - 370

    read more..

  • Page - 371

    read more..

  • Page - 372

    read more..

  • Page - 373

    read more..

  • Page - 374

    read more..

  • Page - 375

    read more..

  • Page - 376

    read more..

  • Page - 377

    read more..

  • Page - 378

    read more..

  • Page - 379

    read more..

  • Page - 380

    read more..

  • Page - 381

    read more..

  • Page - 382

    read more..

  • Page - 383

    read more..

  • Page - 384

    read more..

  • Page - 385

    read more..

  • Page - 386

    read more..

  • Page - 387

    read more..

  • Page - 388

    read more..

  • Page - 389

    read more..

  • Page - 390

    read more..

  • Page - 391

    read more..

  • Page - 392

    read more..

  • Page - 393

    read more..

  • Page - 394

    read more..

  • Page - 395

    read more..

  • Page - 396

    read more..

  • Page - 397

    read more..

  • Page - 398

    read more..

  • Page - 399

    read more..

  • Page - 400

    read more..

  • Page - 401

    read more..

  • Page - 402

    read more..

  • Page - 403

    read more..

  • Page - 404

    read more..

  • Page - 405

    read more..

  • Page - 406

    read more..

  • Page - 407

    read more..

  • Page - 408

    read more..

  • Page - 409

    read more..

  • Page - 410

    test the effective user). -s file file exists and has a length greater than zero. -S file file exists and is a network socket. -t fd fd is a file descriptor directed to/from the terminal. This can be used to determine whether standard input/output/error is being redirected. -u file file exists and is setuid. -w file file exists and read more..

  • Page - 411

    27 – Flow Control: Branching With if The script evaluates the file assigned to the constant FILE and displays its results as the evaluation is performed. There are two interesting things to note about this script. First, notice how the parameter $FILE is quoted within the expressions. This is not read more..

  • Page - 412

    test fi } String Expressions The following expressions are used to evaluate strings: Table 27-2: test String Expressions Expression Is True If... string string is not null. -n string The length of string is greater than zero. -z string The length of string is zero. string1 = string2 string1 == string2 string1 and string2 are equal. Single read more..

  • Page - 413

    27 – Flow Control: Branching With if echo "There is no answer." >&2 exit 1 fi if [ "$ANSWER" = "yes" ]; then echo "The answer is YES." elif [ "$ANSWER" = "no" ]; then echo "The answer is NO." elif [ "$ANSWER" = "maybe" ]; then echo "The answer is MAYBE." else echo "The answer is UNKNOWN." fi read more..

  • Page - 414

    test # test-integer: evaluate the value of an integer. INT=-5 if [ -z "$INT" ]; then echo "INT is empty." >&2 exit 1 fi if [ $INT -eq 0 ]; then echo "INT is zero." else if [ $INT -lt 0 ]; then echo "INT is negative." else echo "INT is positive." fi if [ $((INT % 2)) -eq 0 ]; then echo "INT is even." else echo read more..

  • Page - 415

    27 – Flow Control: Branching With if script this way: #!/bin/bash # test-integer2: evaluate the value of an integer. INT=-5 if [[ "$INT" =~ ^-?[0-9]+$ ]]; then if [ $INT -eq 0 ]; then echo "INT is zero." else if [ $INT -lt 0 ]; then echo "INT is negative." else echo "INT is positive." fi if [ $((INT % 2)) -eq 0 ]; then echo read more..

  • Page - 416

    (( )) - Designed For Integers (( )) - Designed For Integers In addition to the [[ ]] compound command, bash also provides the (( )) com- pound command, which is useful for operating on integers. It supports a full set of arith- metic evaluations, a subject we will cover fully in Chapter 34. (( )) is used read more..

  • Page - 417

    27 – Flow Control: Branching With if nary command, and it deals only with integers, it is able to recognize variables by name and does not require expansion to be performed. We’ll discuss (( )) and the related arithmetic expansion further in Chapter 34. Combining Expressions It’s also possible to combine read more..

  • Page - 418

    Combining Expressions In this script, we determine if the value of integer INT lies between the values of MIN_VAL and MAX_VAL. This is performed by a single use of [[ ]], which includes two expressions separated by the && operator. We could have also coded this using test: if [ $INT -ge read more..

  • Page - 419

    27 – Flow Control: Branching With if echo "$INT is outside $MIN_VAL to $MAX_VAL." else echo "$INT is in range." fi Since all expressions and operators used by test are treated as command arguments by the shell (unlike [[ ]] and (( )) ), characters which have special meaning to bash, such as <, > , read more..

  • Page - 420

    Control Operators: Another Way To Branch command1 && command2 and command1 || command2 It is important to understand the behavior of these. With the && operator, command1 is executed and command2 is executed if, and only if, command1 is successful. With the || operator, command1 is executed and command2 read more..

  • Page - 421

    27 – Flow Control: Branching With if cat <<- _EOF_ <H2>Home Space Utilization (All Users)</H2> <PRE>$(du -sh /home/*)</PRE> _EOF_ else cat <<- _EOF_ <H2>Home Space Utilization ($USER)</H2> <PRE>$(du -sh $HOME)</PRE> _EOF_ fi return } We evaluate the output of the id command. With the -u option, id outputs the read more..

  • Page - 422

    28 – Reading Keyboard Input 28 – Reading Keyboard Input The scripts we have written so far lack a feature common in most computer programs—     interactivity. That is, the ability of the program to interact with the user. While many pro- grams don’t need to be interactive, some programs benefit from being read more..

  • Page - 423

    read more..

  • Page - 424

    read more..

  • Page - 425

    read more..

  • Page - 426

    read more..

  • Page - 427

    read more..

  • Page - 428

    read more..

  • Page - 429

    read more..

  • Page - 430

    Validating Input these safeguards in the interests of economy might be excused if a program is to be used once and only by the author to perform some special task. Even then, if the program per- forms dangerous tasks such as deleting files, it would be wise to include data validation, just in read more..

  • Page - 431

    28 – Reading Keyboard Input This script prompts the user to enter an item. The item is subsequently analyzed to deter- mine its contents. As we can see, the script makes use of many of the concepts that we have covered thus far, including shell functions, [[ ]], (( )), the control operator read more..

  • Page - 432

    Menus echo "Hostname: $HOSTNAME" uptime exit fi if [[ $REPLY == 2 ]]; then df -h exit fi if [[ $REPLY == 3 ]]; then if [[ $(id -u) -eq 0 ]]; then echo "Home Space Utilization (All Users)" du -sh /home/* else echo "Home Space Utilization ($USER)" du -sh $HOME fi exit fi else echo "Invalid entry." >&2 exit 1 fi This script is logically read more..

  • Page - 433

    28 – Reading Keyboard Input Further Reading ● The Bash Reference Manual contains a chapter on builtins, which includes the read command: actionURI(http://www.gnu.org/software/bash/manual/bashref.html#Bash-Builtins):http://www.gnu.org/software/bash/manual/bashref.html#Bash-Builtins 408 read more..

  • Page - 434

    29 – Flow Control: Looping With while / until 29 – Flow Control: Looping With while / until In the previous chapter, we developed a menu-driven program to produce various kinds of system information. The program works, but it still has a significant usability problem. It only executes a single choice and read more..

  • Page - 435

    29 – Flow Control: Looping With while / until tial order from one to five. a bash script could be constructed as follows: #!/bin/bash # while-count: display a series of numbers count=1 while [[ $count -le 5 ]]; do echo $count count=$((count + 1)) done echo "Finished." When executed, this script displays the following: [me@linuxbox ~]$ read more..

  • Page - 436

    Looping DELAY=3 # Number of seconds to display results while [[ $REPLY != 0 ]]; do clear cat <<- _EOF_ Please Select: 1. Display System Information 2. Display Disk Space 3. Display Home Space Utilization 0. Quit _EOF_ read -p "Enter selection [0-3] > " if [[ $REPLY =~ ^[0-3]$ ]]; then if [[ $REPLY == 1 ]]; then echo "Hostname: $HOSTNAME" uptime read more..

  • Page - 437

    29 – Flow Control: Looping With while / until the loop terminates and execution continues with the line following done. Breaking Out Of A Loop bash provides two builtin commands that can be used to control program flow inside loops. The break command immediately terminates a loop, and program control re- sumes read more..

  • Page - 438

    Breaking Out Of A Loop echo "Home Space Utilization ($USER)" du -sh $HOME fi sleep $DELAY continue fi if [[ $REPLY == 0 ]]; then break fi else echo "Invalid entry." sleep $DELAY fi done echo "Program terminated." In this version of the script, we set up an endless loop (one that never terminates on its own) by using read more..

  • Page - 439

    29 – Flow Control: Looping With while / until count=$((count + 1)) done echo "Finished." By changing the test expression to $count -gt 5, until will terminate the loop at the correct time. The decision of whether to use the while or until loop is usually a matter of choosing the one that allows read more..

  • Page - 440

    Reading Files With Loops Here we take the output of the sort command and display the stream of text. However, it is important to remember that since a pipe will execute the loop in a subshell, any vari- ables created or assigned within the loop will be lost when the loop terminates. Summing Up With the read more..

  • Page - 441

    30 – Troubleshooting 30 – Troubleshooting As our scripts become more complex, it’s time to take a look at what happens when things go wrong and they don’t do what we want. In this chapter, we’ll look at some of the common kinds of errors that occur in scripts, and describe a few useful read more..

  • Page - 442

    Syntactic Errors Missing Quotes If we edit our script and remove the trailing quote from the argument following the first echo command: #!/bin/bash # trouble: script to demonstrate common errors number=1 if [ $number = 1 ]; then echo "Number is equal to 1. else echo "Number is not equal to 1." fi watch what happens: [me@linuxbox ~]$ read more..

  • Page - 443

    30 – Troubleshooting while. Let’s look at what happens if we remove the semicolon after the test in the if command: #!/bin/bash # trouble: script to demonstrate common errors number=1 if [ $number = 1 ] then echo "Number is equal to 1." else echo "Number is not equal to 1." fi The result is this: [me@linuxbox ~]$ trouble read more..

  • Page - 444

    Syntactic Errors #!/bin/bash # trouble: script to demonstrate common errors number= if [ $number = 1 ]; then echo "Number is equal to 1." else echo "Number is not equal to 1." fi Running the script with this change results in the output: [me@linuxbox ~]$ trouble /home/me/bin/trouble: line 7: [: =: unary operator expected Number is not equal to read more..

  • Page - 445

    30 – Troubleshooting Then when expansion occurs, the result will be this: [ "" = 1 ] which yields the correct number of arguments. In addition to empty strings, quotes should be used in cases where a value could expand into multi-word strings, as with filenames containing embedded spaces. Logical Errors Unlike syntactic read more..

  • Page - 446

    Logical Errors There is nothing intrinsically wrong with these two lines, as long as the directory named in the variable, dir_name, exists. But what happens if it does not? In that case, the cd command fails and the script continues to the next line and deletes the files in the current working read more..

  • Page - 447

    30 – Troubleshooting Verifying Input A general rule of good programming is that if a program accepts input, it must be able to deal with anything it receives. This usually means that input must be carefully screened, to ensure that only valid input is accepted for further processing. We saw an example read more..

  • Page - 448

    Testing of our work. Let’s look at the file-deletion problem above and see how this could be coded for easy testing. Testing the original fragment of code would be dangerous, since its purpose is to delete files, but we could modify the code to make the test safe: if [[ -d $dir_name ]]; then if cd $dir_name; read more..

  • Page - 449

    30 – Troubleshooting be extensively tested. It's really a matter of determining what is most important. Since it could be so potentially destructive if it malfunctioned, our code fragment deserves careful consideration during both its design and testing. Debugging If testing reveals a problem with a script, the next step read more..

  • Page - 450

    Debugging wrong time. To view the actual flow of the program, we use a technique called tracing. One tracing method involves placing informative messages in a script that display the lo- cation of execution. We can add messages to our code fragment: echo "preparing to delete files" >&2 if [[ -d $dir_name ]]; then if cd read more..

  • Page - 451

    30 – Troubleshooting if [ $number = 1 ]; then echo "Number is equal to 1." else echo "Number is not equal to 1." fi When executed, the results look like this: [me@linuxbox ~]$ trouble + number=1 + '[' 1 = 1 ']' + echo 'Number is equal to 1.' Number is equal to 1. With tracing enabled, we see the commands performed with read more..

  • Page - 452

    Debugging else echo "Number is not equal to 1." fi set +x # Turn off tracing We use the set command with the -x option to activate tracing and the +x option to de- activate tracing. This technique can be used to examine multiple portions of a trouble- some script. Examining Values During Execution It is often read more..

  • Page - 453

    30 – Troubleshooting Further Reading ● The Wikipedia has a couple of short articles on syntactic and logical errors: actionURI(http://en.wikipedia.org/wiki/Syntax_error):http://en.wikipedia.org/wiki/Syntax_error actionURI(http://en.wikipedia.org/wiki/Logic_error):http://en.wikipedia.org/wiki/Logic_error ● There are many online resources for the technical aspects of bash programming: read more..

  • Page - 454

    31 – Flow Control: Branching With case 31 – Flow Control: Branching With case In this chapter, we will continue to look at flow control. In Chapter 28, we constructed some simple menus and built the logic used to act on a user’s selection. To do this, we used a series of if commands to read more..

  • Page - 455

    31 – Flow Control: Branching With case echo "Program terminated." exit fi if [[ $REPLY == 1 ]]; then echo "Hostname: $HOSTNAME" uptime exit fi if [[ $REPLY == 2 ]]; then df -h exit fi if [[ $REPLY == 3 ]]; then if [[ $(id -u) -eq 0 ]]; then echo "Home Space Utilization (All Users)" du -sh /home/* else echo "Home Space Utilization read more..

  • Page - 456

    case 1) echo "Hostname: $HOSTNAME" uptime ;; 2) df -h ;; 3) if [[ $(id -u) -eq 0 ]]; then echo "Home Space Utilization (All Users)" du -sh /home/* else echo "Home Space Utilization ($USER)" du -sh $HOME fi ;; *) echo "Invalid entry" >&2 exit 1 ;; esac The case command looks at the value of word, in our example, the value read more..

  • Page - 457

    31 – Flow Control: Branching With case #!/bin/bash read -p "enter word > " case $REPLY in [[:alpha:]]) echo "is a single alphabetic character." ;; [ABC][0-9]) echo "is A, B, or C followed by a digit." ;; ???) echo "is three characters long." ;; *.txt) echo "is a word ending in '.txt'" ;; *) echo "is something else." ;; esac It is also read more..

  • Page - 458

    case ;; *) echo "Invalid entry" >&2 exit 1 ;; esac Here, we modify the case-menu program to use letters instead of digits for menu selec- tion. Notice how the new patterns allow for entry of both upper- and lowercase letters. Performing Multiple Actions In versions of bash prior to 4.0, case allowed only one action to read more..

  • Page - 459

    31 – Flow Control: Branching With case terminate each action, so now we can do this: #!/bin/bash # case4-2: test a character read -n 1 -p "Type a character > " echo case $REPLY in [[:upper:]]) echo "'$REPLY' is upper case." ;;& [[:lower:]]) echo "'$REPLY' is lower case." ;;& [[:alpha:]]) echo read more..

  • Page - 460

    Further Reading tions: actionURI(http://tldp.org/LDP/abs/html/testbranch.html):http://tldp.org/LDP/abs/html/testbranch.html 435 read more..

  • Page - 461

    32 – Positional Parameters 32 – Positional Parameters One feature that has been missing from our programs is the ability to accept and process command line options and arguments. In this chapter, we will examine the shell features that allow our programs to get access to the contents of the command line. read more..

  • Page - 462

    Accessing The Command Line $1 = $2 = $3 = $4 = $5 = $6 = $7 = $8 = $9 = Even when no arguments are provided, $0 will always contain the first item appearing on the command line, which is the pathname of the program being executed. When argu- ments are provided, we see the results: [me@linuxbox ~]$ posit-param a read more..

  • Page - 463

    32 – Positional Parameters Number of arguments: $# \$0 = $0 \$1 = $1 \$2 = $2 \$3 = $3 \$4 = $4 \$5 = $5 \$6 = $6 \$7 = $7 \$8 = $8 \$9 = $9 " The result: [me@linuxbox ~]$ posit-param a b c d Number of arguments: 4 $0 = /home/me/bin/posit-param $1 = a $2 = b $3 = c $4 = d $5 = $6 = $7 = $8 = $9 = shift – Getting Access read more..

  • Page - 464

    Accessing The Command Line $8 = Desktop $9 = dirlist-bin.txt On this example system, the wildcard * expands into 82 arguments. How can we process that many? The shell provides a method, albeit a clumsy one, to do this. The shift command causes all the parameters to “move down one” each time it is read more..

  • Page - 465

    32 – Positional Parameters #!/bin/bash # file_info: simple file information program PROGNAME=$(basename $0) if [[ -e $1 ]]; then echo -e "\nFile Type:" file $1 echo -e "\nFile Status:" stat $1 else echo "$PROGNAME: usage: $PROGNAME file" >&2 exit 1 fi This program displays the file type (determined by the file command) and the file read more..

  • Page - 466

    Accessing The Command Line fi } Now, if a script that incorporates the file_info shell function calls the function with a filename argument, the argument will be passed to the function. With this capability, we can write many useful shell functions that can not only be used in scripts, but also within the .bashrc read more..

  • Page - 467

    32 – Positional Parameters #!/bin/bash # posit-params3 : script to demonstrate $* and $@ print_params () { echo "\$1 = $1" echo "\$2 = $2" echo "\$3 = $3" echo "\$4 = $4" } pass_params () { echo -e "\n" '$* :'; print_params $* echo -e "\n" '"$*" :'; print_params "$*" echo -e "\n" '$@ :'; print_params $@ read more..

  • Page - 468

    Handling Positional Parameters En Masse $2 = words with spaces $3 = $4 = With our arguments, both $! and $@ produce a four word result: word words with spaces "$*" produces a one word result: "word words with spaces" "$@" produces a two word result: "word" "words with spaces" which matches our actual intent. The read more..

  • Page - 469

    32 – Positional Parameters filename= while [[ -n $1 ]]; do case $1 in -f | --file) shift filename=$1 ;; -i | --interactive) interactive=1 ;; -h | --help) usage exit ;; *) usage >&2 exit 1 ;; esac shift done First, we add a shell function called usage to display a message when the help option is invoked or an unknown option is read more..

  • Page - 470

    A More Complete Application ;; Q|q) echo "Program terminated." exit ;; *) continue ;; esac elif [[ -z $filename ]]; then continue else break fi done fi If the interactive variable is not empty, an endless loop is started, which contains the filename prompt and subsequent existing file-handling code. If the desired output file read more..

  • Page - 471

    32 – Positional Parameters if touch $filename && [[ -f $filename ]]; then write_html_page > $filename else echo "$PROGNAME: Cannot write file '$filename'" >&2 exit 1 fi else write_html_page fi The code that handles the logic of the -f option appears at the end of the listing shown above. In it, we test for the existence read more..

  • Page - 472

    Summing Up } report_disk_space () { cat <<- _EOF_ <H2>Disk Space Utilization</H2> <PRE>$(df -h)</PRE> _EOF_ return } report_home_space () { if [[ $(id -u) -eq 0 ]]; then cat <<- _EOF_ <H2>Home Space Utilization (All Users)</H2> <PRE>$(du -sh /home/*)</PRE> _EOF_ else cat <<- _EOF_ <H2>Home Space Utilization ($USER)</H2> <PRE>$(du -sh read more..

  • Page - 473

    32 – Positional Parameters interactive= filename= while [[ -n $1 ]]; do case $1 in -f | --file) shift filename=$1 ;; -i | --interactive) interactive=1 ;; -h | --help) usage exit ;; *) usage >&2 exit 1 ;; esac shift done # interactive mode if [[ -n $interactive ]]; then while true; do read -p "Enter name of output file: " filename if [[ -e $filename ]]; read more..

  • Page - 474

    Summing Up write_html_page fi We’re not done yet. There are still more things we can do and improvements we can make. Further Reading ● The Bash Hackers Wiki has a good article on positional parameters: actionURI(http://wiki.bash-hackers.org/scripting/posparams):http://wiki.bash-hackers.org/scripting/posparams ● The Bash Reference Manual has an article read more..

  • Page - 475

    33 – Flow Control: Looping With for 33 – Flow Control: Looping With for In this final chapter on flow control, we will look at another of the shell’s looping con- structs. The for loop differs from the while and until loops in that it provides a means of processing sequences during a loop. read more..

  • Page - 476

    for: Traditional Shell Form The really powerful feature of for is the number of interesting ways we can create the list of words. For example, through brace expansion: [me@linuxbox ~]$ for i in {A..D}; do echo $i; done A B C D or pathname expansion: [me@linuxbox ~]$ for i in distros*.txt; do echo $i; done distros-by-date.txt distros-dates.txt read more..

  • Page - 477

    33 – Flow Control: Looping With for In this example, we look for the longest string found within a file. When given one or more filenames on the command line, this program uses the strings program (which is included in the GNU binutils package) to generate a list of readable text “words” in each read more..

  • Page - 478

    for: Traditional Shell Form The basis of this tradition comes from the Fortran programming language. In For- tran, undeclared variables starting with the letters I, J, K, L, and M are automati- cally typed as integers, while variables beginning with any other letter are typed as real (numbers with decimal read more..

  • Page - 479

    33 – Flow Control: Looping With for When executed, it produces the following output: [me@linuxbox ~]$ simple_counter 0 1 2 3 4 In this example, expression1 initializes the variable i with the value of zero, expression2 allows the loop to continue as long as the value of i remains less than 5, and expression3 read more..

  • Page - 480

    Summing Up local format="%8s%10s%10s\n" local i dir_list total_files total_dirs total_size user_name if [[ $(id -u) -eq 0 ]]; then dir_list=/home/* user_name="All Users" else dir_list=$HOME user_name=$USER fi echo "<H2>Home Space Utilization ($user_name)</H2>" for i in $dir_list; do total_files=$(find $i -type f | wc -l) total_dirs=$(find $i -type d | wc -l) read more..

  • Page - 481

    34 – Strings And Numbers 34 – Strings And Numbers Computer programs are all about working with data. In past chapters, we have focused on processing data at the file level. However, many programming problems need to be solved using smaller units of data such as strings and numbers. In this chapter, we will read more..

  • Page - 482

    Parameter Expansion If we perform this sequence, the result will be nothing, because the shell will try to ex- pand a variable named a_file rather than a. This problem can be solved by adding braces: [me@linuxbox ~]$ echo "${a}_file" foo_file We have also seen that positional parameters greater than 9 can read more..

  • Page - 483

    34 – Strings And Numbers default value if unset [me@linuxbox ~]$ echo $foo default value if unset [me@linuxbox ~]$ foo=bar [me@linuxbox ~]$ echo ${foo:="default value if unset"} bar [me@linuxbox ~]$ echo $foo bar Note: Positional and other special parameters cannot be assigned this way. ${parameter:?word} If parameter is unset or empty, this expansion read more..

  • Page - 484

    Parameter Expansion Expansions That Return Variable Names The shell has the ability to return the names of variables. This is used in some rather ex- otic situations. ${!prefix*} ${!prefix@} This expansion returns the names of existing variables with names beginning with prefix. According to the bash documentation, both forms read more..

  • Page - 485

    34 – Strings And Numbers [me@linuxbox ~]$ echo ${foo:5:6} string If the value of offset is negative, it is taken to mean it starts from the end of the string rather than the beginning. Note that negative values must be preceded by a space to pre- vent confusion with the ${parameter:-word} expansion. length, if read more..

  • Page - 486

    Parameter Expansion file ${parameter/pattern/string} ${parameter//pattern/string} ${parameter/#pattern/string} ${parameter/%pattern/string} This expansion performs a search-and-replace upon the contents of parameter. If text is found matching wildcard pattern, it is replaced with the contents of string. In the normal form, only the first occurrence of read more..

  • Page - 487

    34 – Strings And Numbers max_len=$len max_word=$j fi done echo "$i: '$max_word' ($max_len characters)" fi shift done Next, we will compare the efficiency of the two versions by using the time command: [me@linuxbox ~]$ time longest-word2 dirlist-usr-bin.txt dirlist-usr-bin.txt: 'scrollkeeper-get-extended-content-list' (38 characters) real 0m3.618s user 0m1.544s sys 0m1.768s read more..

  • Page - 488

    Parameter Expansion verting all of the characters in the user's input to either lower or uppercase and ensure that the database entries are normalized the same way. The declare command can be used to normalize strings to either upper or lowercase. Using declare, we can force a variable to always contain the read more..

  • Page - 489

    34 – Strings And Numbers character to uppercase (capitalization). Here is a script that demonstrates these expansions: #!/bin/bash # ul-param - demonstrate case conversion via parameter expansion if [[ $1 ]]; then echo ${1,,} echo ${1,} echo ${1^^} echo ${1^} fi Here is the script in action: read more..

  • Page - 490

    Arithmetic Evaluation And Expansion Number Bases Back in Chapter 9, we got a look at octal (base 8) and hexadecimal (base 16) numbers. In arithmetic expressions, the shell supports integer constants in any base. Table 34-2: Specifying Different Number Bases Notation Description number By default, numbers without any notation are read more..

  • Page - 491

    34 – Strings And Numbers * Multiplication / Integer division ** Exponentiation % Modulo (remainder) Most of these are self-explanatory, but integer division and modulo require further dis- cussion. Since the shell’s arithmetic only operates on integers, the results of division are always whole numbers: [me@linuxbox ~]$ echo $(( 5 / 2 )) 2 read more..

  • Page - 492

    Arithmetic Evaluation And Expansion When executed, the results look like this: [me@linuxbox ~]$ modulo <0> 1 2 3 4 <5> 6 7 8 9 <10> 11 12 13 14 <15> 16 17 18 19 <20> Assignment Although its uses may not be immediately apparent, arithmetic expressions may perform assignment. We have performed assignment many times, though read more..

  • Page - 493

    34 – Strings And Numbers parameter = value Simple assignment. Assigns value to parameter. parameter += value Addition. Equivalent to parameter = parameter + value. parameter -= value Subtraction. Equivalent to parameter = parameter – value. parameter *= value Multiplication. Equivalent to parameter = parameter * value. parameter /= value Integer read more..

  • Page - 494

    Arithmetic Evaluation And Expansion 2 If we assign the value of one to the variable foo and then increment it with the ++ opera- tor placed after the parameter name, foo is returned with the value of one. However, if we look at the value of the variable a second time, we see the incremented value. read more..

  • Page - 495

    34 – Strings And Numbers << Left bitwise shift. Shift all the bits in a number to the left. >> Right bitwise shift. Shift all the bits in a number to the right. & Bitwise AND. Perform an AND operation on all the bits in two numbers. | Bitwise OR. Perform an OR operation on all the bits in two read more..

  • Page - 496

    Arithmetic Evaluation And Expansion == Equal to != Not equal to && Logical AND || Logical OR expr1?expr2:expr3 Comparison (ternary) operator. If expression expr1 evaluates to be non-zero (arithmetic true) then expr2, else expr3. When used for logical operations, expressions follow the rules of arithmetic logic; that is, expressions that read more..

  • Page - 497

    34 – Strings And Numbers When attempted, bash will declare an error: [me@linuxbox ~]$ a=0 [me@linuxbox ~]$ ((a<1?a+=1:a-=1)) bash: ((: a<1?a+=1:a-=1: attempted assignment to non-variable (error token is "-=1") This problem can be mitigated by surrounding the assignment expression with parenthe- ses: [me@linuxbox ~]$ ((a<1?(a+=1):(a-=1))) Next, we read more..

  • Page - 498

    Arithmetic Evaluation And Expansion [me@linuxbox ~]$ arith-loop a a**2 a**3 = ==== ==== 0 0 0 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000 bc – An Arbitrary Precision Calculator Language We have seen how the shell can handle all types of integer arithmetic, but what if we need to perform read more..

  • Page - 499

    34 – Strings And Numbers Using bc If we save the bc script above as foo.bc, we can run it this way: [me@linuxbox ~]$ bc foo.bc bc 1.06.94 Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc. This is free software with ABSOLUTELY NO WARRANTY. For details type `warranty'. 4 If we look carefully, we can see the result read more..

  • Page - 500

    bc – An Arbitrary Precision Calculator Language An Example Script As a real-world example, we will construct a script that performs a common calculation, monthly loan payments. In the script below, we use a here document to pass a script to bc: #!/bin/bash # loan-calc : script to calculate monthly loan payments read more..

  • Page - 501

    34 – Strings And Numbers 1270.7222490000 This example calculates the monthly payment for a $135,000 loan at 7.75% APR for 180 months (15 years). Notice the precision of the answer. This is determined by the value given to the special scale variable in the bc script. A full description of the bc read more..

  • Page - 502

    Further Reading ● as well as a description of the formula for calculating loan payments used in our loan-calc script: actionURI(http://en.wikipedia.org/wiki/Amortization_calculator):http://en.wikipedia.org/wiki/Amortization_calculator 477 read more..

  • Page - 503

    35 – Arrays 35 – Arrays In the last chapter, we looked at how the shell can manipulate strings and numbers. The data types we have looked at so far are known in computer science circles as scalar vari- ables; that is, variables that contain a single value. In this chapter, we will look at read more..

  • Page - 504

    Creating An Array [me@linuxbox ~]$ a[1]=foo [me@linuxbox ~]$ echo ${a[1]} foo Here we see an example of both the assignment and access of an array element. With the first command, element 1 of array a is assigned the value “foo”. The second command displays the stored value of element 1. The use of read more..

  • Page - 505

    35 – Arrays [5]=Fri [6]=Sat) Accessing Array Elements So what are arrays good for? Just as many data-management tasks can be performed with a spreadsheet program, many programming tasks can be performed with arrays. Let’s consider a simple data-gathering and presentation example. We will construct a script that examines the read more..

  • Page - 506

    Accessing Array Elements # Check that argument is a directory if [[ ! -d $1 ]]; then usage exit 1 fi # Initialize array for i in {0..23}; do hours[i]=0; done # Collect data for i in $(stat -c %y "$1"/* | cut -c 12-13); do j=${i/#0} ((++hours[j])) ((++count)) done # Display data echo -e "Hour\tFiles\tHour\tFiles" echo -e "----\t-----\t----\t-----" for i read more..

  • Page - 507

    35 – Arrays Array Operations There are many common array operations. Such things as deleting arrays, determining their size, sorting, etc. have many applications in scripting. Outputting The Entire Contents Of An Array The subscripts * and @ can be used to access every element in an array. As with posi- tional parameters, read more..

  • Page - 508

    Array Operations [me@linuxbox ~]$ a[100]=foo [me@linuxbox ~]$ echo ${#a[@]} # number of array elements 1 [me@linuxbox ~]$ echo ${#a[100]} # length of element 100 3 We create array a and assign the string “foo” to element 100. Next, we use parameter ex- pansion to examine the length of the array, using the @ notation. read more..

  • Page - 509

    35 – Arrays [me@linuxbox ~]$ foo=(a b c) [me@linuxbox ~]$ echo ${foo[@]} a b c [me@linuxbox ~]$ foo+=(d e f) [me@linuxbox ~]$ echo ${foo[@]} a b c d e f Sorting An Array Just as with spreadsheets, it is often necessary to sort the values in a column of data. The shell has no direct way of doing this, but it's not hard read more..

  • Page - 510

    Array Operations [me@linuxbox ~]$ unset foo [me@linuxbox ~]$ echo ${foo[@]} [me@linuxbox ~]$ unset may also be used to delete single array elements: [me@linuxbox ~]$ foo=(a b c d e f) [me@linuxbox ~]$ echo ${foo[@]} a b c d e f [me@linuxbox ~]$ unset 'foo[2]' [me@linuxbox ~]$ echo ${foo[@]} a b d e f In this example, we delete the third element read more..

  • Page - 511

    35 – Arrays declare -A colors colors["red"]="#ff0000" colors["green"]="#00ff00" colors["blue"]="#0000ff" Unlike integer indexed arrays, which are created by merely referencing them, associative arrays must be created with the declare command using the new -A option. Associa- tive array elements are read more..

  • Page - 512

    36 – Exotica 36 – Exotica In this, the final chapter of our journey, we will look at some odds and ends. While we have certainly covered a lot of ground in the previous chapters, there are many bash fea- tures that we have not covered. Most are fairly obscure, and useful mainly to those inte- read more..

  • Page - 513

    36 – Exotica { ls -l; echo "Listing of foo.txt"; cat foo.txt; } > output.txt Using a subshell is similar: (ls -l; echo "Listing of foo.txt"; cat foo.txt) > output.txt Using this technique we have saved ourselves some typing, but where a group command or subshell really shines is with pipelines. When constructing a pipeline of read more..

  • Page - 514

    Group Commands And Subshells /usr/bin/zipsplit root root /usr/bin/zjsdecode root root /usr/bin/zsoelim root root File owners: daemon : 1 read more..

  • Page - 515

    36 – Exotica 27 echo 28 29 # List owners 30 echo "File owners:" 31 { for i in "${!owners[@]}"; do 32 printf "%-10s: %5d file(s)\n" "$i" ${owners["$i"]} 33 done } | sort 34 echo 35 36 read more..

  • Page - 516

    Group Commands And Subshells array[@]}" expansion which expands into the list of array indexes rather than the list of array elements. Process Substitution While they look similar and can both be used to combine streams for redirection, there is an important difference between group commands and subshells. Whereas a read more..

  • Page - 517

    36 – Exotica Process substitution allows us to treat the output of a subshell as an ordinary file for pur- poses of redirection. In fact, since it is a form of expansion, we can examine its real value: [me@linuxbox ~]$ echo <(echo "foo") /dev/fd/63 By using echo to view the result of the expansion, read more..

  • Page - 518

    Group Commands And Subshells Links: 1 Attributes: -rw-r--r-- Filename: bin Size: 4096 Owner: me Group: me Modified: 2009-07-10 07:31 Links: 2 Attributes: drwxr-xr-x Filename: bookmarks.html Size: 394213 Owner: me Group: me Traps In Chapter 10, we saw how programs read more..

  • Page - 519

    36 – Exotica trap "echo 'I am ignoring you.'" SIGINT SIGTERM for i in {1..5}; do echo "Iteration $i of 5" sleep 5 done This script defines a trap that will execute an echo command each time either the SIG- INT or SIGTERM signal is received while the script is running. Execution of the pro- gram looks like read more..

  • Page - 520

    Traps for i in {1..5}; do echo "Iteration $i of 5" sleep 5 done This script features two trap commands, one for each signal. Each trap, in turn, speci- fies a shell function to be executed when the particular signal is received. Note the inclu- sion of an exit command in each of the signal-handling read more..

  • Page - 521

    36 – Exotica A better way is to use the mktemp program (not to be confused with the mktemp standard library function) to both name and create the temporary file. The mk- temp program accepts a template as an argument that is used to build the file- name. The template should include a series of read more..

  • Page - 522

    Asynchronous Execution #!/bin/bash # async-parent : Asynchronous execution demo (parent) echo "Parent: starting..." echo "Parent: launching child script..." async-child & pid=$! echo "Parent: child (PID= $pid) launched." echo "Parent: continuing..." sleep 2 echo "Parent: pausing to wait for child to finish..." wait $pid echo "Parent: child is finished. read more..

  • Page - 523

    36 – Exotica Parent: launching child script... Parent: child (PID= 6741) launched. Parent: continuing... Child: child is running... Parent: pausing to wait for child to finish... Child: child is done. Exiting. Parent: child is finished. Continuing... Parent: parent is done. Exiting. Named Pipes In most Unix-like systems, it is possible to create a special type read more..

  • Page - 524

    Named Pipes Here we use mkfifo to create a named pipe called pipe1. Using ls, we examine the file and see that the first letter in the attributes field is “p”, indicating that it is a named pipe. Using Named Pipes To demonstrate how the named pipe works, we will need two terminal windows (or read more..

  • Page - 525

    36 – Exotica ● The Advanced Bash-Scripting Guide also has a discussion of process substitution: actionURI(http://tldp.org/LDP/abs/html/process-sub.html):http://tldp.org/LDP/abs/html/process-sub.html ● Linux Journal has two good articles on named pipes. The first, from September 1997: actionURI(http://www.linuxjournal.com/article/2156):http://www.linuxjournal.com/article/2156 ● and the second, read more..

  • Page - 526

    Index Index A a2ps command...................................................333 absolute pathnames................................................9 alias command.............................................50, 126 aliases.....................................................42, 50, 124 American National Standards Institute (see ANSI) ............................................................................160 American Standard Code for read more..

  • Page - 527

    Index break command..........................................412, 445 broken links..........................................................39 BSD style............................................................111 buffering.............................................................182 bugs............................................................422, 424 build environment..............................................346 bzip2 read more..

  • Page - 528

    Index data compression................................................226 data redundancy.................................................226 data validation....................................................389 date command........................................................4 date formats........................................................273 dd command.......................................................190 read more..

  • Page - 529

    Index word-splitting..............................................74p. expressions............................................................... arithmetic........................70, 453, 464, 467, 479 conditional............................................396, 420 ext3.....................................................................188 extended regular expressions.............................254 Extensible Markup Language............................265 F read more..

  • Page - 530

    Index Free Software Foundation............................xix, xxi fsck command....................................................189 ftp command..............................199, 207, 342, 370 FTP servers.................................................200, 370 FUNCNAME variable.......................................441 function statement..............................................374 G read more..

  • Page - 531

    Index Joliet extensions.................................................192 Joy, Bill..............................................................137 K kate command....................................................131 KDE.....................................2, 27, 40, 95, 131, 208 kedit command...................................................131 kernel...xvi, xixp., 46, 108, 118, 174, 183, 287, 350 key read more..

  • Page - 532

    Index viewing usage...............................................121 virtual............................................................111 menu-driven programs.......................................406 meta key...............................................................81 meta sequences...................................................246 metacharacters....................................................246 read more..

  • Page - 533

    Index patch command..................................................287 patches................................................................285 PATH variable............................126, 129, 356, 374 pathname expansion...............................68, 75, 451 pathnames..........................................................260 absolute.............................................................9 read more..

  • Page - 534

    Index Readline...............................................................79 README.....................................................49, 344 redirection................................................................ blocked pipe.................................................499 group commands and subshells....................487 here documents.............................................369 here strings...................................................404 read more..

  • Page - 535

    Index stat command.....................................................223 sticky bit...............................................................98 storage devices...................................................176 audio CDs.............................................180, 191 CD-ROMs.........................................179p., 191 creating file systems.....................................185 device read more..

  • Page - 536

    Index lowercase to uppercase conversion..............289 numbering lines....................................267, 305 paginating.....................................................313 pasting..........................................................280 preparing for printing...................................329 removing duplicate lines................................61 rendering in PostScript.................................320 ROT13 read more..

  • Page - 537

    Index vfat.....................................................................188 vi command........................................................136 vim command.............................................263, 359 virtual consoles......................................................5 Virtual Private Network.....................................206 virtual terminals.....................................................5 visual read more..

  • Page - 538

    Index /usr/share..............................................................22 /usr/share/dict.....................................................247 /usr/share/doc.................................................22, 49 /var.......................................................................23 /var/log.................................................................23 /var/log/messages...................................23, 64, 183 read more..

Write Your Review