POSIX sh下字符串替换触发SC2039错误,求合规实现方案
Let’s work through this issue together. Your original Bash-specific string replacement works fine in Bash, but it’s not supported in POSIX sh—hence the ShellCheck SC2039 error. The two attempts you made didn’t pan out because you tried using Bash parameter expansion syntax directly in a pipeline, which isn’t valid; pipelines expect actual commands, not variable expansion shorthand.
The POSIX-compliant Solution
We can use the tr command (a core POSIX-standard tool) to delete the target characters cleanly. Here’s how to adjust your code:
# Define the special characters we want to remove (simplified from your original equivalence classes) special_chars='!@#$%&' PASS="e@0cc3auZeeSio&G" # Use printf to safely pass the string to tr, which deletes the specified characters PASS2=$(printf '%s' "$PASS" | tr -d "$special_chars") # Verify the result echo "$PASS2" # Output: e0cc3auZeeSioG
Why This Works
printf '%s' "$PASS"safely outputs the password string without altering it (unlikeecho, which can have unexpected behavior with certain special characters or flags).tr -d "$special_chars"is a POSIX-standard command that deletes every occurrence of the characters in$special_charsfrom the input stream.
Note on Your Original special_chars Definition
Your original special_chars used POSIX equivalence classes like [=!=], which are designed to match characters considered equivalent in the current locale. For most use cases (especially if you just want to delete !, @, #, $, %, &), simplifying to raw characters is straightforward and effective. If you need to retain equivalence class syntax for locale compatibility, you can adapt the tr command to use them, but raw characters are sufficient for this scenario.
内容的提问来源于stack exchange,提问作者Sashank Sekhar Singh

