Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Correctly print subshells nested in a variable expansion #32

Merged
merged 1 commit into from
Jan 3, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion libdash/printer.py
Original file line number Diff line number Diff line change
Expand Up @@ -393,7 +393,14 @@ def string_of_arg_char (c, quote_mode=UNQUOTED):
elif (type == "Q"):
return "\"" + string_of_arg (param, quote_mode=QUOTED) + "\"";
elif (type == "B"):
return "$(" + to_string (param) + ")";
body = to_string (param)
# to handle $( () )
try:
if body[0] == "(" and body[-1] == ")":
body = f" {body} "
except IndexError:
pass
return "$(" + body + ")"
else:
abort ();

Expand Down
8 changes: 6 additions & 2 deletions ocaml/ast.ml
Original file line number Diff line number Diff line change
Expand Up @@ -462,8 +462,12 @@ and string_of_arg_char ?quote_mode:(quote_mode=QUnquoted) = function
| V (vt,nul,name,a) ->
"${" ^ name ^ (if nul then ":" else "") ^ string_of_var_type vt ^ string_of_arg ~quote_mode a ^ "}"
| Q a -> "\"" ^ string_of_arg ~quote_mode:QQuoted a ^ "\""
| B t -> "$(" ^ to_string t ^ ")"

| B t ->
let s = to_string t in
if String.length s >= 2 && s.[0] = '(' && s.[String.length s - 1] = ')' then
"$( " ^ s ^ " )"
else
"$(" ^ s ^ ")"
and string_of_arg ?quote_mode:(quote_mode=QUnquoted) = function
| [] -> ""
| c :: a ->
Expand Down
4 changes: 4 additions & 0 deletions test/tests/nested_shell_in_subshell.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
( (echo abc) )
echo $( (echo abc) )
echo `(echo abc)`
echo $()