Skip to content

Warn against variable substring removal #2290

@hseg

Description

@hseg

For new checks and feature suggestions

Here's a snippet or screenshot that shows the problem:

#!/bin/bash
base="[hello] [world]"
pref="[hello]
suff="[world]"
pref="${base%$suff}"
# sets to $base, not "hello ", because $base doesn't end in any of the characters d,l,o,r,w

Here's what shellcheck currently says:

Nothing

Here's what I wanted or expected to see:

Warning: the substring removal expansion accepts a pattern, not a literal string.
Use slicing operators instead:

"${base%suff}" -> "${base:0:${#base}-${#suff}}"
"${base#pref}" -> "${base:${#pref}}"

(note: this advice isn't perfect for suffixes, since if the "suffix" is longer than the base, this will silently remove len(suff)-len(base) characters from the end of $base)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions