Introduction to Bash
Notes
Tilde Expansion
We can use ~
and the name of a user if we want to retrieve the home directory of a specific user.
echo ~codio
Tilde expansion lets us work in a user’s home directory even if we don’t know their user name.
We can use tilde + plus ~+
to represent the PWD
, or to present the current directory that we’re working in.
We can use tilde + dash ~-
to represent the OLDPWD
, or the previous directory you were in if you’ve changed directories.
Brace Expansion
touch file_{1..3}{a..c}
Parameter expansion
allows us to retrieve and modify stored values. The symbol for this is ${...}
.
Let’s set a parameter in the terminal:
book="Where the Sidewalk Ends"
We can retrieve the value of the parameter with a dollar sign $
and the name of the parameter.
echo $book
For example, echo ${book:6}
returns the parameter’s value starting with the sixth character in the string.
echo ${book:6}
Pattern Substitution
Pattern substitution is a parameter expansion feature that lets us obtain a value and change it depending on a pattern. This is commonly used for replacing a word or character using the pattern below.
echo ${variableName/oldWord/newWord}
Below is a complete pattern substitution example.
echo ${book/Ends/Begins}
In Pattern Substitution, one slash after the parameter replaces the first instance of a match, and two slashes replaces them all.
Let’s replace all e’s with ampersands &
using two forward slashes //
.
echo ${book//e/&}
Now, let’s do the same thing with only one slash.
echo ${book/e/&}
Named Character Classes
Named character classes are used to print values that have been given a name. Their value is determined by the LC_CTYPE
locale. A few examples include:
[:alnum:]
: Prints all files that include alphabets and numbers. Both lower and uppercase letters are taken into account.[:alpha:]
: Prints all files that exclusively contain alphabets. Both lower and uppercase letters are taken into account.[:digit:]
: prints all files that include digits.[:lower:]
: prints all files with lower-case letters.[:punct:]
: prints all files that include punctuation characters, including:! " # $ % &' () * +, –. /: ; = >? @ [] '|
.
[:space:]
: prints all files that contain space characters.[:upper:]
: prints all files with upper-case letters.
Last updated