Skip to content

Files

Latest commit

 

History

History
40 lines (27 loc) · 1.42 KB

SC2295.md

File metadata and controls

40 lines (27 loc) · 1.42 KB

Pattern: Unquoted expansion inside ${..}

Issue: -

Description

When using expansions in a parameter expansion prefix/suffix expression, the expansion needs to be quoted separately or it will match as a pattern. The quotes around the outer parameter expansion does not protect against this.

This means that any variable that contains e.g. brackets, asterisks or question marks may not match as expected. In the example, [1933] was interpreted as a pattern character range and would therefore match /tmp/King_Kong_3/ but not /tmp/King_Kong_[1933]/ as was the intention.

Example of incorrect code:

relative_path() {
  printf '%s\n' "${2#$1}"
}

# Results in "/tmp/King_Kong_[1933]/extras/trailer.mkv" because the prefix fails to match
relative_path "/tmp/King_Kong_[1933]/" "/tmp/King_Kong_[1933]/extras/trailer.mkv"

# Results in "cover.jpg" even though the prefix is different
relative_path "/tmp/King_Kong_[1933]/" "/tmp/King_Kong_3/cover.jpg"

Example of correct code:

relative_path() {
  printf '%s\n' "${2#"$1"}"
}
# Results in "extras/trailer.mkv" as expected
relative_path "/tmp/King_Kong_[1933]/" "/tmp/King_Kong_[1933]/extras/trailer.mkv"

# Results in "/tmp/King_Kong_3/cover.jpg" as expected
relative_path "/tmp/King_Kong_[1933]/" "/tmp/King_Kong_3/cover.jpg"

Further Reading