git/list[1] front-page[2] threads[3] people[4] search[5] about
 

Re: contrib/completion/git-completion.bash: declare -g is not portable

From
Jeff King <peff@peff.net>
Date
Feb 3, 2018, 20:22 UTC
Message-ID
<20180203202234.GA13374@sigill.intra.peff.net>
In-Reply-To
<87lgg9g8cr.fsf@linux-m68k.org>
On Sat, Feb 03, 2018 at 08:51:16PM +0100, Andreas Schwab wrote:
Show 9 quoted lines
> On Feb 03 2018, Torsten Bögershausen <tboegi@web.de> wrote:
> 
> > What is "declare -g" good for ?
> 
>       -g        create global variables when used in a shell function; otherwise
>                 ignored
> 
>     When used in a function, `declare' makes NAMEs local, as with the `local'
>     command.  The `-g' option suppresses this behavior.

I think the bigger question is why one would use "declare -g" instead of just assigning the variable with "var=value".

Glancing at the code, I suspect it is because the name of the variable itself needs expanded. If that's the case, we could use eval instead, like:

diff --git a/contrib/completion/git-completion.bash b/contrib/completion/git-completion.bash
index 3cc815be0d..204d620ff7 100644
--- a/contrib/completion/git-completion.bash
+++ b/contrib/completion/git-completion.bash
@@ -297,7 +297,7 @@ __gitcomp_builtin ()
 	eval "options=\$$var"
 
 	if [ -z "$options" ]; then
-		declare -g "$var=$(__git ${cmd/_/ } --git-completion-helper)"
+		eval "$var=\$(__git \${cmd/_/ } --git-completion-helper)"
 		eval "options=\$$var"
 	fi
 

-Peff
Previous: Andreas SchwabNext: Duy Nguyen
Message 3 of 6 in “contrib/completion/git-completion.bash: declare -g is not portable”
  1. Torsten BögershausenFeb 3, 2018
  2. Andreas SchwabFeb 3, 2018
  3. Jeff KingFeb 3, 2018
  4. Duy NguyenFeb 4, 2018
  5. Eric SunshineFeb 4, 2018
  6. Lucas WerkmeisterFeb 4, 2018

Read the whole thread, see it on lore, or plain text.

$ cat FOOTERMessages come from the public archive at lore.kernel.org/git, fetched every hour. The front page is chosen and written each morning by an AI editor and can be wrong; the threads themselves are the record. About and API. For agents: an MCP server at https://gitlist.dev/mcp, and any thread, story or person page as Markdown by adding .md to its URL (or sending Accept: text/markdown). Details in /llms.txt.