Search code examples
functionzsh

Having hard time writing a relatively simple zsh function where I try to surround an input with single quotes


I have the following function in my .zshrc file:

function tgss() {
    input=("$@")  # Store input arguments as array to avoid escaping double quotes
    escaped_input="${input[*]}"  # Join array elements into a string

    result=$(terragrunt state show "$escaped_input")
    echo "$result"
}

The function is supposed to get a terragrunt state resource entry just as it is displayed by the output of terragrunt state list (aws_sqs_queue.default["subscription-name-number"]) and run terragrunt state show on this resource.

When I run:

tgss aws_sqs_queue.default["subscription-name-number"]

I get the following error:

zsh: no matches found: aws_sqs_queue.default[subscription-name-number]

I believe it's somehow related to the double quotes, so I'm looking for a way to edit my function so it surrounds the input with single quotes, like this:

tgss 'tgss aws_sqs_queue.default["subscription-name-number"]'

Without me actually adding the single quotes.

Is that possible?


Solution

  • Short answer: you need to add the single-quotes when you run the function/command (or at least quote/escape the [ and " characters).

    You can't "fix" this in a function, because the problem occurs before the function runs (in fact, before the shell has even figured out what command/function to run).

    It happens while the shell is parsing the command line. One of the steps it does is trying to expand any words that contain wildcard characters (that aren't in quotes or escaped) into lists of matching filenames. Since tgss aws_sqs_queue.default["subscription-name-number"] contains [...], it's eligible for this. So the shell tries to find files matching "tgss aws_sqs_queue.default[one of those characters]", fails, and prints an error message to that effect.

    To put it another way, in shell syntax the argument aws_sqs_queue.default["subscription-name-number"] means "pass a list of filenames matching this pattern, each as a separate argument". You're trying to make your function bypass standard shell syntax, and you just can't do that.