Keep a command's words together across a redirect in shell_command's segments

This commit is contained in:
2026-10-22 02:31:04 +02:00
parent 3e8f9deef6
commit 18c284c1fe
4 changed files with 17 additions and 9 deletions
+6 -3
View File
@@ -7,6 +7,8 @@ import shlex
HEREDOC = re.compile(r"<<-?[ \t]*([\"']?)([A-Za-z_]\w*)\1[^\n]*\n.*?^[ \t]*\2[ \t]*$", re.DOTALL | re.MULTILINE)
ASSIGNMENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]*=")
OPERATOR = set("\n();&|<>")
# A redirect operator on its own: a command goes on around it.
REDIRECT = re.compile(r"&?[<>]+[&|]?")
# A quoted string or an escape is taken whole, so a # inside one starts no comment; a comment starts a word.
PIECE = re.compile(r"""'[^']*'|"(?:\\.|[^"\\])*"|\\.|(?<![^\s;&|()])#[^\n]*""", re.DOTALL)
@@ -29,11 +31,10 @@ def simple_commands(command: str, cwd: str, home: str) -> list[Simple]:
def segments(command: str) -> list[list[str]]:
"""The command's simple commands as lists of words, split at ; & | ( ) < > and line breaks, without redirect targets. Shell forms it does not parse:
"""The command's simple commands as lists of words, split at ; & | ( ) and line breaks, without redirect targets. Shell forms it does not parse:
- a quoted string is one word, so `bash -c "git commit"` and `echo "$(git commit)"` hide the inner command;
- a backtick substitution stays inside its words, while `$(git commit)` outside quotes splits into the `$` and a command of its own;
- a keyword or a brace opens its command's words, so `then git commit` reads as the command `then`;
- a redirect splits a command in two, so `git > out commit` reads as `git` and `commit`;
- `<(...)` and `<<<` read as redirects, so the word after them is dropped as the target;
- a file descriptor before a redirect, as in `2>&1`, stays a word;
- a heredoc's body is dropped;
@@ -49,8 +50,10 @@ def segments(command: str) -> list[list[str]]:
for token in tokens:
if target:
target = False
elif set(token) <= OPERATOR and token:
elif REDIRECT.fullmatch(token):
# A redirect's target is not an operand.
target = True
elif set(token) <= OPERATOR and token:
target = "<" in token or ">" in token
found.append([])
elif found[-1] or not ASSIGNMENT.match(token):