13  Shell Expansions

13.1 Wildcards

    • Matches any sequence of characters.
  • ? Matches a single character.
  • […] Matches any character within the brackets.
  • [^...] Matches any character NOT in the brackets.

13.2 Tilde Expansion

Tilde Expansion:

  • ~ Expands to the home directory of the current user.
  • ~username Expands to the home directory of the specified username.

13.3 Variable/Parameter Expansion

Shell variables are placeholders for storing data. When you reference a variable, the shell expands it to its stored value.

  • $variable: Expands to the value of the specified variable.
  • ${variable}: Use curly braces for disambiguation.

https://www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html#Shell-Parameter-Expansion

https://opensource.com/article/17/6/bash-parameter-expansion

13.4 Command Substitution

Command substitution allows you to execute a command and replace it with its output. - $(command): Executes the command and substitutes its output.

examples:

files_count=$(ls -l | wc -l) echo "Number of files: $files_count" 

13.5 Arithmetic Expansion

Arithmetic expressions enclosed in double parentheses $((…)) are evaluated and the result is expanded.

Example:

Prints: y is 10

x=5 y=$((x * 2)) echo "y is $y" 

13.6 Brace Expansion

Brace expansion generates multiple strings by specifying a sequence or multiple options inside curly braces.

{a,b,c}: Expands to “a”, “b”, and “c”. {start..end}: Expands a alphanumerical range.

Examples:

Prints: apple banana cherry

echo {apple,banana,cherry}

Prints: 1 2 3 4 5

echo {1..5}

13.7 Common Applications

13.7.1 Remove the extension (.zip) from all the filenames

Note: the – protects against filenames that begin with - and would appear to be an option otherwise.

for f in *.zip; do mv -- "$f" "${f%.zip}"; done

13.7.2 Replace extension (.foo to .bar) for all filenames

for f in *.foo; do mv -- "$f" "${f%.foo}.bar"; done

13.7.3 Remove prefix abc_ from all filenames

for f in abc_* ; do mv -- "$f" "${f#abc_}"; done

13.7.4 Replace all spaces with underscores

for f in *\ *; do mv -- "$f" "${f// /_}"; done

13.7.5 Convert filenames to all lowercase

for f in *[[:upper:]]*; do mv -- "$f" "${f,,}"; done