Table of Contents for
Learn Linux Shell Scripting - Fundamentals of Bash 4.4

Version ebook / Retour

Cover image for bash Cookbook, 2nd Edition Learn Linux Shell Scripting - Fundamentals of Bash 4.4 by Sebastiaan Tammer Published by Packt Publishing, 2018
  1. Learn Linux Shell Scripting - Fundamentals of Shell 4.4
  2. Title Page
  3. Copyright and Credits
  4. Learn Linux Shell Scripting – Fundamentals of Bash 4.4
  5. About Packt
  6. Why subscribe?
  7. PacktPub.com
  8. Contributors
  9. About the author
  10. About the reviewer
  11. Packt is searching for authors like you
  12. Table of Contents
  13. Preface
  14. Who this book is for
  15. What this book covers
  16. To get the most out of this book
  17. Download the example code files
  18. Download the color images
  19. Conventions used
  20. Get in touch
  21. Reviews
  22. Disclaimer
  23. Introduction
  24. What is Linux?
  25. What is Bash?
  26. Summary
  27. Setting Up Your Local Environment
  28. Technical requirements
  29. Choosing between a virtual machine and a physical installation
  30. Setting up VirtualBox
  31. Creating an Ubuntu virtual machine
  32. Creating the virtual machine in VirtualBox
  33. Installing Ubuntu on the virtual machine
  34. Accessing the virtual machine via SSH
  35. Summary
  36. Questions
  37. Further reading
  38. Choosing the Right Tools
  39. Technical requirements
  40. Using graphical editors for shell scripting
  41. Atom
  42. Atom installation and configuration
  43. Notepad++
  44. Using command-line editors
  45. Vim
  46. Vim summary
  47. .vimrc
  48. Vim cheat sheet
  49. nano
  50. Combining graphical editors with command-line editors when writing shell scripts
  51. Summary
  52. Questions
  53. Further reading
  54. The Linux Filesystem
  55. Technical requirements
  56. The Linux filesystem explained
  57. What is a filesystem?
  58. What makes the Linux filesystem unique?
  59. Structure of the Linux filesystem
  60. Tree structure
  61. Overview of top-level directories
  62. What about multiple partitions?
  63. /bin/, /sbin/, and /usr/
  64. /etc/
  65. /opt/, /tmp/, and /var/
  66. Everything is a file
  67. Different types of files
  68. Summary
  69. Questions
  70. Further reading
  71. Understanding the Linux Permissions Scheme
  72. Technical requirements
  73. Read, write, and execute
  74. RWX
  75. Users, groups, and others
  76. Manipulating file permissions and ownership
  77. chmod, umask
  78. sudo, chown, and chgrp
  79. sudo
  80. chown, chgrp
  81. Working with multiple users
  82. Advanced permissions
  83. File attributes
  84. Special file permissions
  85. Access Control Lists (ACLs)
  86. Summary
  87. Questions
  88. Further reading
  89. File Manipulation
  90. Technical requirements
  91. Common file operations
  92. Copying
  93. Removing
  94. Renaming, moving, and linking
  95. Archiving
  96. Finding files
  97. locate
  98. find
  99. Summary
  100. Questions
  101. Further reading
  102. Hello World!
  103. Technical requirements
  104. First steps
  105. The shebang
  106. Running scripts
  107. Readability
  108. Comments
  109. Script header
  110. Verbosity
  111. Verbosity in comments
  112. Verbosity of commands
  113. Verbosity of command output
  114. Keep It Simple, Stupid (KISS)
  115. Summary
  116. Questions
  117. Further reading
  118. Variables and User Input
  119. Technical requirements
  120. What is a variable?
  121. Why do we need variables?
  122. Variables or constants?
  123. Variable naming
  124. Dealing with user input
  125. Basic input
  126. Parameters and arguments
  127. Interactive versus non-interactive scripts
  128. Combining positional arguments and read
  129. Summary
  130. Questions
  131. Further reading
  132. Error Checking and Handling
  133. Technical requirements
  134. Error checking
  135. Exit status
  136. Functional checks
  137. Test shorthand
  138. Variable refresher
  139. Bash debugging
  140. Error handling
  141. if-then-exit
  142. if-then-else
  143. Shorthand syntax
  144. Error prevention
  145. Checking arguments
  146. Managing absolute and relative paths
  147. Dealing with y/n
  148. Summary
  149. Questions
  150. Further reading
  151. Regular Expressions
  152. Technical requirements
  153. Introducing regular expressions
  154. What is a regular expression?
  155. grep
  156. Greediness
  157. Character matching
  158. Line anchors
  159. Character classes
  160. Globbing
  161. What is globbing?
  162. Similarities with regular expressions
  163. More globbing
  164. Advanced globbing
  165. Disabling globbing, and other options
  166. Using regular expressions with egrep and sed
  167. Advanced grep
  168. Introducing egrep
  169. sed, the stream editor
  170. Stream editing
  171. In-place editing
  172. Line manipulation
  173. Final remarks
  174. Summary
  175. Questions
  176. Further reading
  177. Conditional Testing and Scripting Loops
  178. Technical requirements
  179. Advanced if-then-else
  180. A recap on if-then-else 
  181. Using regular expressions in tests
  182. The elif condition
  183. Nesting
  184. Getting help
  185. The while loop
  186. The until loop
  187. Creating an interactive while loop
  188. The for loop
  189. Globbing and the for loop
  190. Loop control
  191. Breaking the loop
  192. The continue keyword
  193. Loop control and nesting
  194. Summary
  195. Questions
  196. Further reading
  197. Using Pipes and Redirection in Scripts
  198. Technical requirements
  199. Input/output redirection
  200. File descriptors
  201. Redirecting output
  202. stdout
  203. stderr
  204. Redirect all output
  205. Special output redirection
  206. /dev/null
  207. /dev/zero
  208. Input redirection
  209. Generating a password
  210. Advanced redirecting
  211. Redirecting redirections
  212. Command substitution
  213. Process substitution
  214. Pipes
  215. Binding stdout to stdin
  216. Practical examples
  217. Yet another password generator
  218. Setting passwords in a script
  219. tee
  220. Here documents
  221. Heredocs and variables
  222. Using heredocs for script input
  223. Here strings
  224. Summary
  225. Questions
  226. Further reading
  227. Functions
  228. Technical requirements
  229. Functions explained
  230. Hello world!
  231. More complexity
  232. Variable scopes
  233. Practical examples
  234. Error handling
  235. Augmenting functions with parameters
  236. Colorful
  237. Returning values
  238. Function libraries
  239. Source
  240. More practical examples
  241. Current working directory
  242. Type checking
  243. Yes-no check
  244. Summary
  245. Questions
  246. Further reading
  247. Scheduling and Logging
  248. Technical requirements
  249. Scheduling with at and cron
  250. at
  251. Time syntax
  252. The at queue
  253. at output
  254. cron
  255. crontab
  256. Syntax for the crontab
  257. Logging script results
  258. Crontab environment variables
  259. PATH
  260. SHELL
  261. MAILTO
  262. Logging with redirection
  263. Final logging considerations
  264. A note on verbosity
  265. Summary
  266. Questions
  267. Further reading
  268. Parsing Bash Script Arguments with getopts
  269. Technical requirements
  270. Positional parameters versus flags
  271. Using flags on the command line
  272. The getopts shell builtin
  273. The getopts syntax
  274. Multiple flags
  275. Flags with arguments
  276. Combining flags with positional arguments
  277. Summary
  278. Questions
  279. Further reading
  280. Bash Parameter Substitution and Expansion
  281. Technical requirements
  282. Parameter expansion
  283. Parameter substitutions – recap
  284. Default values
  285. Input checking
  286. Parameter length
  287. Variable manipulation
  288. Pattern substitution
  289. Pattern removal
  290. Case modification
  291. Substring expansion
  292. Summary
  293. Questions
  294. Further reading
  295. Tips and Tricks with Cheat Sheet
  296. Technical requirements
  297. General tips and tricks
  298. Arrays
  299. The history command
  300. Creating your own aliases
  301. Command-line shortcuts
  302. Fun with exclamation marks
  303. Running commands from the history
  304. Keyboard shortcuts
  305. Copying and pasting from the terminal
  306. Reverse search
  307. Cheat sheet for interactive commands
  308. Navigation
  309. cd
  310. ls
  311. pwd
  312. File manipulation
  313. cat
  314. less
  315. touch
  316. mkdir
  317. cp
  318. rm
  319. mv
  320. ln
  321. head
  322. tail
  323. Permissions and ownership
  324. chmod
  325. umask
  326. chown
  327. chgrp
  328. sudo
  329. su
  330. useradd
  331. groupadd
  332. usermod
  333. Summary
  334. Final words
  335. Assessments
  336. Chapter 2
  337. Chapter 3
  338. Chapter 4
  339. Chapter 5
  340. Chapter 6
  341. Chapter 7
  342. Chapter 8
  343. Chapter 9
  344. Chapter 10
  345. Chapter 11
  346. Chapter 12
  347. Chapter 13
  348. Chapter 14
  349. Chapter 15
  350. Chapter 16
  351. Other Books You May Enjoy
  352. Leave a review - let other readers know what you think

stdout

Most output from commands will be standard output, written to stdout on /dev/fd/1. By using the > symbol, we can redirect this out with the following syntax:

command > output-file

A redirect will always be made to a file (however, as we know, not all files are equal, so after the regular examples, we'll show you some Bash magic where non-regular files are concerned). If the file does not exist, it will be created. If it does exist, it will be overwritten.

In its simplest form, everything that would normally be printed to your Terminal can be redirected to a file:

reader@ubuntu:~/scripts/chapter_12$ ls -l /var/log/dpkg.log 
-rw-r--r-- 1 root root 737150 Nov 5 18:49 /var/log/dpkg.log
reader@ubuntu:~/scripts/chapter_12$ cat /var/log/dpkg.log > redirected-file.log
reader@ubuntu:~/scripts/chapter_12$ ls -l
total 724
-rw-rw-r-- 1 reader reader 737150 Nov 5 19:45 redirected-file.log

As you know, cat prints the whole file content to your Terminal. In reality, it actually sends the whole content to stdout, which is bound to /dev/fd/1, which is bound to your Terminal; this is why you see it.

Now, if we redirect the content of the file back to another file, we've essentially made a great effort to... copy a file! From the file sizes you can see that it is actually the same file. If you're unsure, you can use the diff command to see if the files are the same:

reader@ubuntu:~/scripts/chapter_12$ diff /var/log/dpkg.log redirected-file.log 
reader@ubuntu:~/scripts/chapter_12$ echo $?
0

If diff does not return any output, and it has an exit code of 0, there are no differences in the file.

Back to the redirection example. We used > to redirect the output to the file. In reality, > is shorthand for 1>. You might recognize this 1: it refers to the file descriptor /dev/fd/1. As we'll see when we're dealing with stderr, which is on /dev/fd/2, we will use 2> instead of 1> or >.

First, however, let's build a simple script to illustrate this a little bit further:

reader@ubuntu:~/scripts/chapter_12$ vim redirect-to-file.sh 
reader@ubuntu:~/scripts/chapter_12$ cat redirect-to-file.sh
#!/bin/bash

#####################################
# Author: Sebastiaan Tammer
# Version: v1.0.0
# Date: 2018-11-05
# Description: Redirect user input to file.
# Usage: ./redirect-to-file.sh
#####################################

# Capture the users' input.
read -p "Type anything you like: " user_input

# Save the users' input to a file.
echo ${user_input} > redirect-to-file.txt

Now, when we run this, read will prompt us to input some text. This will be saved in the user_input variable. Then, we'll use echo to send the content of the user_input variable to stdout. But, instead of it reaching the Terminal on /dev/pts/0 via /dev/fd/1, we redirect it to the redirect-to-file.txt file.

All in all, it looks something like this:

reader@ubuntu:~/scripts/chapter_12$ bash redirect-to-file.sh 
Type anything you like: I like dogs! And cats. Maybe a gecko?
reader@ubuntu:~/scripts/chapter_12$ ls -l
total 732
-rw-rw-r-- 1 reader reader 737150 Nov 5 19:45 redirected-file.log
-rw-rw-r-- 1 reader reader 383 Nov 5 19:58 redirect-to-file.sh
-rw-rw-r-- 1 reader reader 38 Nov 5 19:58 redirect-to-file.txt
reader@ubuntu:~/scripts/chapter_12$ cat redirect-to-file.txt
I like dogs! And cats. Maybe a gecko?

Now, this works as advertised. However, if we run it again, we see two things that can go wrong with this script:

reader@ubuntu:~/scripts$ bash chapter_12/redirect-to-file.sh
Type anything you like: Hello
reader@ubuntu:~/scripts$ ls -l
<SNIPPED>
drwxrwxr-x 2 reader reader 4096 Nov 5 19:58 chapter_12
-rw-rw-r-- 1 reader reader 6 Nov 5 20:02 redirect-to-file.txt
reader@ubuntu:~/scripts$ bash chapter_12/redirect-to-file.sh
Type anything you like: Bye
reader@ubuntu:~/scripts$ ls -l
<SNIPPED>
drwxrwxr-x 2 reader reader 4096 Nov 5 19:58 chapter_12
-rw-rw-r-- 1 reader reader 4 Nov 5 20:02 redirect-to-file.txt

The first thing that goes wrong, which we've warned about before, is that relative paths might mess up where the file is written.

You might have envisioned that the file was created right next to the script; this will only happen if your current working directory is in the directory where the script is. Because we call it from lower in the tree, the output is written there (since that is the current working directory).

The other problem is that each time we type something in, we remove the old content of the file! After we type Hello, we see that the file is six bytes (one byte for each character, plus a newline), and after we typed Bye, we now see that the file is only four bytes (three characters plus the newline).

This might be the desired behavior, but more often than not it is much nicer if the output is appended to the file, instead of replacing it.

Let's solve both issues in a new version of the script:

reader@ubuntu:~/scripts$ vim chapter_12/redirect-to-file.sh 
reader@ubuntu:~/scripts$ cat chapter_12/redirect-to-file.sh
#!/bin/bash

#####################################
# Author: Sebastiaan Tammer
# Version: v1.1.0
# Date: 2018-11-05
# Description: Redirect user input to file.
# Usage: ./redirect-to-file.sh
#####################################

# Since we're dealing with paths, set current working directory.
cd $(dirname $0)

# Capture the users' input.
read -p "Type anything you like: " user_input

# Save the users' input to a file. > for overwrite, >> for append.
echo ${user_input} >> redirect-to-file.txt

Now, if we run it (from wherever), we'll see that new text gets appended to the first sentence, I like dogs! And cats. Maybe a gecko? in the /home/reader/chapter_12/redirect-to-file.txt file:

reader@ubuntu:~/scripts$ cd /tmp/
reader@ubuntu:/tmp$ cat /home/reader/scripts/chapter_12/redirect-to-file.txt
I like dogs! And cats. Maybe a gecko?
reader@ubuntu:/tmp$ bash /home/reader/scripts/chapter_12/redirect-to-file.sh
Type anything you like: Definitely a gecko, those things are awesome!
reader@ubuntu:/tmp$ cat /home/reader/scripts/chapter_12/redirect-to-file.txt
I like dogs! And cats. Maybe a gecko?
Definitely a gecko, those things are awesome!

So, cd $(dirname $0) helped us with our relative paths, and a >> instead of > ensured appending instead of overwriting. As you might expect, >> is again short for 1>>, as we will see when we start redirecting stderr streams in a bit.

A little while back, we promised you some Bash magic. While not exactly magic, it might hurt your head just a little:

reader@ubuntu:~/scripts/chapter_12$ cat redirect-to-file.txt 
I like dogs! And cats. Maybe a gecko?
Definitely a gecko, those things are awesome!
reader@ubuntu:~/scripts/chapter_12$ cat redirect-to-file.txt > /dev/pts/0
I like dogs! And cats. Maybe a gecko?
Definitely a gecko, those things are awesome!
reader@ubuntu:~/scripts/chapter_12$ cat redirect-to-file.txt > /dev/fd/1
I like dogs! And cats. Maybe a gecko?
Definitely a gecko, those things are awesome!
reader@ubuntu:~/scripts/chapter_12$ cat redirect-to-file.txt > /dev/fd/2
I like dogs! And cats. Maybe a gecko?
Definitely a gecko, those things are awesome!

So, we've managed to print our file using cat a total of four times. We could have done that with for as well, you might be thinking, but the lesson is not the amount of times we printed the message, but how we did it!

First, we just used cat; nothing special there. Next, we used cat in combination with a redirection of stdout to /dev/pts/0, our Terminal. Again, the message is printed.

The third and fourth times, we sent the redirected stdout of cat to /dev/fd/1 and /dev/fd/2. Since these are symlinked to /dev/pts/0, it's not really surprising that these also end up on our Terminal.

How then do we actually differentiate between stdout and stderr?