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

The for loop

The for loop can be considered the more powerful loop in Bash scripting. In practice, for and while are interchangeable, but for has better shorthand syntax. This means that to write a loop in for often requires much less code than an equivalent while loop.

The for loop has two different syntaxes: a C-style syntax and the regular Bash syntax. We'll first look at the Bash syntax:

FOR value IN list-of-values DO thing-with-value DONE

A for loop allows us to iterate over a list of things. Each loop will use a different item in that list, in a sequential order. This very simple example should illustrate this behavior:

reader@ubuntu:~/scripts/chapter_11$ vim for-simple.sh
reader@ubuntu:~/scripts/chapter_11$ cat for-simple.sh
#!/bin/bash

#####################################
# Author: Sebastiaan Tammer
# Version: v1.0.0
# Date: 2018-10-27
# Description: Simple for syntax.
# Usage: ./for-simple.sh
#####################################

# Create a 'list'.
words="house dog telephone dog"

# Iterate over the list and process the values.
for word in ${words}; do
echo "The word is: ${word}"
done

reader@ubuntu:~/scripts/chapter_11$ bash for-simple.sh
The word is: house
The word is: dog
The word is: telephone
The word is: dog

As you can see, for takes a list (in this case, a string delimited by whitespace), and for each value it finds it performs the echo action. We've added some extra text there so that you can see that it actually goes into the loop four times and does not just print the list with extra new lines. The main thing to notice here is that in the echo we use the ${word} variable, which we defined as the second word in the for definition. This means that for every run of the for loop, the value of the ${word} variable is different (which is very much using a variable as it is intended, with a variable content!). You can name this anything, but we prefer to give semantically logical names; since we called our list words, an item in that list would be a word.

If you want to do the same thing with while, things are going to get a lot more complicated. It's definitely possible by using a counter and a command such as cut (which allows you to cut out different parts of a string), but since the for loop does it in this simple manner, why bother?

The second syntax that we can use with for will be more recognizable for those experienced with other scripting programming languages. This C-style syntax uses a counter that increments until a certain point, not unlike the example we saw when we looked at while. The syntax is as follows:

FOR ((counter=0; counter<=10; counter++)); DO something DONE

Seems pretty similar right? Check out this example script:

reader@ubuntu:~/scripts/chapter_11$ vim for-counter.sh 
reader@ubuntu:~/scripts/chapter_11$ cat for-counter.sh
#!/bin/bash

#####################################
# Author: Sebastiaan Tammer
# Version: v1.0.0
# Date: 2018-10-27
# Description: Example of a for loop in C-style syntax.
# Usage: ./for-counter.sh
#####################################

# This loop runs 10 times.
for ((counter=1; counter<=10; counter++)); do
echo "Hello! This is loop number ${counter}."
sleep 1
done

# After the for-loop finishes, print a goodbye message.
echo "All done, thanks for tuning in!"

reader@ubuntu:~/scripts/chapter_11$ bash for-counter.sh
Hello! This is loop number 1.
Hello! This is loop number 2.
Hello! This is loop number 3.
Hello! This is loop number 4.
Hello! This is loop number 5.
Hello! This is loop number 6.
Hello! This is loop number 7.
Hello! This is loop number 8.
Hello! This is loop number 9.
Hello! This is loop number 10.
All done, thanks for tuning in!

Again, due to the nature of off-by-one errors, we have to use slightly different numbers. Since the counter is incremented at the end of the loop, we need to start it at 1 instead of 0 (or we could have done the same in the while loop). In C-style syntax, <= means smaller than or equal to, and ++ means increment by 1. So, we have a counter that starts at 1, continues until it reaches 10, and is incremented by 1 for each run of the loop. We find this for loop preferable to the equivalent while loop; it needs less code and is more common in other scripting/programming languages.

Even better, there is a way to iterate over a number range (as we did for 1–10 previously), with the for loop Bash syntax as well. Because a number range is nothing more than a list of numbers, we can use almost the same syntax as we did in the first example, in which we iterated over a list of words. Take a look at the following code:

reader@ubuntu:~/scripts/chapter_11$ vim for-number-list.sh
reader@ubuntu:~/scripts/chapter_11$ cat for-number-list.sh
#!/bin/bash

#####################################
# Author: Sebastiaan Tammer
# Version: v1.0.0
# Date: 2018-10-27
# Description: Example of a for loop with a number range.
# Usage: ./for-number-list.sh
#####################################

# This loop runs 10 times.
for counter in {1..10}; do
echo "Hello! This is loop number ${counter}."
sleep 1
done

# After the for-loop finishes, print a goodbye message.
echo "All done, thanks for tuning in!"

reader@ubuntu:~/scripts/chapter_11$ bash for-number-list.sh
Hello! This is loop number 1.
Hello! This is loop number 2.
Hello! This is loop number 3.
Hello! This is loop number 4.
Hello! This is loop number 5.
Hello! This is loop number 6.
Hello! This is loop number 7.
Hello! This is loop number 8.
Hello! This is loop number 9.
Hello! This is loop number 10.
All done, thanks for tuning in!

So, the syntax for <variable> in <list> works with a list of {1..10}. This is called brace expansion and was added in Bash version 4. The syntax for brace expansion is quite simple:

{<starting value>..<ending value>}

Brace expansion can be used in many ways, but printing lists of numbers or characters is the most well-known:

reader@ubuntu:~/scripts/chapter_11$ echo {1..5}
1 2 3 4 5
reader@ubuntu:~/scripts/chapter_11$ echo {a..f}
a b c d e f

The brace expansion {1..5} returns the string 1 2 3 4 5, which is a whitespace delimited list of values and can thus be used in the Bash-style for loop! Alternatively, {a..f} prints the string a b c d e f. The range is actually determined by ASCII hexadecimal codes; this allows us to do the following as well:

reader@ubuntu:~/scripts/chapter_11$ echo {A..z}
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ ] ^ _ ` a b c d e f g h i j k l m n o p q r s t u v w x y z

It might seem weird that you'll see some special characters printed halfway, but those are in-between the uppercase and lowercase Latin alphabet characters. Note that this syntax is very similar to getting the value of a variable with ${variable} (however, that is parameter expansion and not brace expansion).

The brace expansion has one other interesting piece of functionality: it allows us to define the increment! Simply put, this allows us to tell Bash how many steps to skip each time we increment. The syntax for this is as follows:

{<starting value>..<ending value>..<increment>}

By default, the increment value is 1. If this is the desired functionality, we can omit the increment value, as we previously saw. If we do set it, however, we'll see something like the following:

reader@ubuntu:~/scripts/chapter_11$ echo {1..100..10}
1 11 21 31 41 51 61 71 81 91
reader@ubuntu:~/scripts/chapter_11$ echo {0..100..10}
0 10 20 30 40 50 60 70 80 90 100

Now, the increment is done in steps of 10. As you can see in the previous example, the <ending value> is considered inclusive. This means that values that are lower or equal will be printed, but others will not. The next value in the first brace expansion in the preceding example. {1..100..10}, would have been 101; since this is not lower or equal to 100, the value is not printed and the expansion is terminated.

Finally, since we promised that anything we could do with while we could also do with for, we'd like to end this part of the chapter by showing you how you would create an infinite loop with for. This is the most common reason to choose while over for, because the for syntax is a little weird:

eader@ubuntu:~/scripts/chapter_11$ vim for-infinite.sh 
reader@ubuntu:~/scripts/chapter_11$ cat for-infinite.sh
#!/bin/bash


#####################################
# Author: Sebastiaan Tammer
# Version: v1.0.0
# Date: 2018-10-27
# Description: Example of an infinite for loop.
# Usage: ./for-infinite.sh
#####################################

# Infinite for loop.
for ((;;)); do
echo "Hello!"
sleep 1 # Wait for 1 second.
done

reader@ubuntu:~/scripts/chapter_11$ bash for-infinite.sh
Hello!
Hello!
Hello!
^C

We use the C-style syntax, but we omit the initialization, comparison, and incrementing of the counter. Therefore, it reads as follows:

for ((<nothing>;<no-comparison>;<no-increment>)); do

This ends up as ((;;));, which only makes sense if you put it in the context of the normal syntax, as we did in the previous example. We could also just omit either the increment or the comparison to the same effect, but that would do the same thing with more code. Often, shorter is better, since it will be clearer.

Try to replicate the infinite for loop, but only by omitting a single value from the for clause. If you get that working, you'll be a step closer to understanding why you have now made it unending. If you need a little nudge, perhaps you'd want to echo the value of counter in the loop so that you can see what is happening. Or you could always run it with bash -x, of course!