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

Tree structure

Let's start by logging in to our virtual machine via SSH:

ssh -p 2222 reader@localhost

Enter your password at the prompt and you should arrive at the default Ubuntu 18.04 login banner, which should look similar to the following:

reader@localhost's password: 
Welcome to Ubuntu 18.04.1 LTS (GNU/Linux 4.15.0-29-generic x86_64)
<SNIPPED>
System information as of Sat Jul 28 14:15:19 UTC 2018

System load: 0.09 Processes: 87
Usage of /: 45.6% of 9.78GB Users logged in: 0
Memory usage: 15% IP address for enp0s3: 10.0.2.15
Swap usage: 0%
<SNIPPED>
Last login: Sat Jul 28 14:13:42 2018 from 10.0.2.2
reader@ubuntu:~$

When logging in (either via SSH or the Terminal console) you will end up at the home directory of the user. You can always find out where you are exactly by using the pwd command. pwd stands for print working directory:

reader@ubuntu:~$ pwd
/home/reader

So, we've ended up in the /home/reader/ directory. This is the default for most Linux distributions: /home/$USERNAME/. Since we created the primary user reader, this is where we expect to be. For those of you coming from Windows, this might look very foreign: where is the drive name (C:, D:, and so on) and why are we using (forward) slashes instead of backslashes?

Linux, as well as Unix and other Unix-like systems, uses a tree structure. It is referred to as a tree because it starts at a single origin point, the root (found at /). Directories are nested from there (like branches from a tree), not much differently from other operating systems. Finally, the tree structure ends in files that are considered the leaves of the tree. This might sound terribly complicated still, but it's actually relatively simple. Let's keep exploring to make sure we fully understand this structure! Under Linux, we use the cd command to change directories. It works by entering cd, followed by the location on the filesystem where we want to go as the argument to the command. Navigate to the filesystem root:

reader@ubuntu:~$ cd /    
reader@ubuntu:/$

As you can see, nothing much seems to have happened. However, there is one tiny difference in your Terminal prompt: the ~ character has been replaced by /. Under Ubuntu, the default configuration shows the location on the filesystem without needing to use the pwd command. The prompt is built as follows: <username>@<hostname>:<location>$. Why the ~ then? Simple: the tilde character is shorthand for the user's home directory! If the shorthand wasn't there, the prompt at login would be reader@ubuntu:/home/reader$.

Since we have navigated to the root of the filesystem, let's check out what we can find there. To list the contents of the current directory, we use the ls command:

reader@ubuntu:/$ ls
bin dev home initrd.img.old lib64 media opt root sbin srv sys usr vmlinuz
boot etc initrd.img lib lost+found mnt proc run snap swap.img tmp var vmlinuz.old

If you're using SSH, you'll most likely have some colors to differentiate between files and directories (and even permissions on directories, if you see tmp in a different manner; this will be discussed in the next chapter). However, even with color assistance, this still feels unclear. Let's clean it up a bit by using an option on the ls command:

reader@ubuntu:/$ ls -l
total 2017372
drwxr-xr-x 2 root root 4096 Jul 28 10:31 bin
drwxr-xr-x 3 root root 4096 Jul 28 10:32 boot
drwxr-xr-x 19 root root 3900 Jul 28 10:31 dev
drwxr-xr-x 90 root root 4096 Jul 28 10:32 etc
drwxr-xr-x 3 root root 4096 Jun 30 18:20 home
lrwxrwxrwx 1 root root 33 Jul 27 11:39 initrd.img -> boot/initrd.img-4.15.0-29-generic
lrwxrwxrwx 1 root root 33 Jul 27 11:39 initrd.img.old -> boot/initrd.img-4.15.0-23-generic
drwxr-xr-x 22 root root 4096 Apr 26 19:09 lib
drwxr-xr-x 2 root root 4096 Apr 26 19:07 lib64
drwx------ 2 root root 16384 Jun 30 17:58 lost+found
drwxr-xr-x 2 root root 4096 Apr 26 19:07 media
drwxr-xr-x 2 root root 4096 Apr 26 19:07 mnt
drwxr-xr-x 2 root root 4096 Apr 26 19:07 opt
dr-xr-xr-x 97 root root 0 Jul 28 10:30 proc
drwx------ 3 root root 4096 Jul 1 09:40 root
drwxr-xr-x 26 root root 920 Jul 28 14:15 run
drwxr-xr-x 2 root root 12288 Jul 28 10:31 sbin
drwxr-xr-x 4 root root 4096 Jun 30 18:20 snap
drwxr-xr-x 2 root root 4096 Apr 26 19:07 srv
-rw------- 1 root root 2065694720 Jun 30 18:00 swap.img
dr-xr-xr-x 13 root root 0 Jul 28 10:30 sys
drwxrwxrwt 9 root root 4096 Jul 28 14:32 tmp
drwxr-xr-x 10 root root 4096 Apr 26 19:07 usr
drwxr-xr-x 13 root root 4096 Apr 26 19:10 var
lrwxrwxrwx 1 root root 30 Jul 27 11:39 vmlinuz -> boot/vmlinuz-4.15.0-29-generic
lrwxrwxrwx 1 root root 30 Jul 27 11:39 vmlinuz.old -> boot/vmlinuz-4.15.0-23-generic

The option -l (hyphen lowercase l, as in long) to ls gives the long listing format. Among other things, this prints the permissions, the owner of the file/directory, the type of file, and its size. Remember, permissions and ownership are discussed in the next chapter, so no need to worry about this for now. The most important thing to take away from this is that each file/directory is printed on its own line, where the first character of that line denotes the type of file: d for directory, - for regular file, and l for symlinks (which are shortcuts under Linux).

Let's navigate deeper into the tree structure, back toward our home directory. At this point, you have two options. You can use a relative path (as in: relative to the current location) or a fully qualified path (which is not relative to the current directory). Let's try both:

reader@ubuntu:/$ cd home
reader@ubuntu:/home$

The preceding is an example of changing directories into a relative directory. We were positioned in the root directory, /, and we navigated to home from there, effectively ending up in /home. We could have navigated there from anywhere by using the fully qualified path:

reader@ubuntu:/$ cd /home
reader@ubuntu:/home$

Did you spot the difference? In the fully qualified example, the argument to cd started with a slash, but in the relative example it did not. Let's see what happens if you use both types incorrectly:

reader@ubuntu:/home$ ls
reader
reader@ubuntu:/home$ cd /reader
-bash: cd: /reader: No such file or directory

We listed the contents of the /home directory with ls. As expected, we saw (at least) the current user's home directory, reader. However, when we tried to navigate to it using cd /reader, we got the infamous error No such file or directory. This is not surprising though: there isn't actually a directory /reader. The directory we're looking for is /home/reader, which would be reached fully qualified with the command cd /home/reader:

reader@ubuntu:/home$ cd home
-bash: cd: home: No such file or directory
reader@ubuntu:/home$

The same error is presented if we try to use an incorrect relative path. In the preceding example, we are currently located in the /home directory and we use the cd home command. Effectively, this would put us in /home/home, which, as we saw when we used ls in the /home directory, does not exist!

The safest way to navigate around Linux is fully qualified: as long as you have the correct directory, it always works, no matter where you are currently located on the filesystem. However, especially when you get deeper into the filesystem, you're typing a lot more. We always recommend beginning users to start with fully qualified navigation and switch to relative once they're comfortable with the cd, ls, and pwd commands.

Even though fully qualified is safer, it's much less efficient then relative. You saw how we can move deeper into the branches of the tree structure, but what if you had to go down a level, back toward the root? Luckily for us, that does not force us to use fully qualified paths. We can use the .. notation, which means as much as go up a level toward /:

reader@ubuntu:/home$ cd ..
reader@ubuntu:/$
A note on terminology is in order here. While we conceptualized the filesystem as a tree, when talking about the root directory, we consider this as the highest point in the filesystem. So when moving from / to /home, we're moving down. If we use the command cd .. to move back to /, we're moving up. While we think that this doesn't really match with the picture of a tree (where the root is actually the lowest point), please remember this convention!

Using cd .. to move up lands us back at the root of the filesystem. At this point, you might think If I do this again while I'm on the highest level of the filesystem, what would happen?. Give it a try:

reader@ubuntu:/$ cd ..
reader@ubuntu:/$

Fortunately for us, we do not get an error nor a crashing machine; instead, we just end up (or, depending on how you look at it, stay) on the root of the filesystem.

A source of confusion among new users of Linux is often the term root. It can stand for any of three things:
  1. The lowest point in the filesystem, at /
  2. The default superuser, named just root
  3. The default superuser's home directory, at /root/

Often, it is left to the reader to use context to determine which of the three is meant. When talking in the context of filesystems, it will probably be:
   
  1. If it seems to be referring to a user, you can expect it to mean the root user
  2. Only when talking about the root user's home directory or /root/ should  you think of
  3. Most often, you will encounter root to mean either 1 or 2!