2

I am trying to understand how the set command works on fish shell.

For example, to remove the greeting message, the fish manual suggests to:

To empty the text, with the default greeting function:

set -U fish_greeting 

or set -g fish_greeting in config.fish.

But why it is suggested to use set -g fish_greeting in config.fish instead of just set fish_greeting? What is the practical purpose of -g here?

1 Answer 1

6

If a variable already exists, set without "-g" will update it.

I.e. if you have a local variable called "fish_greeting", then set fish_greeting will change that local variable.

If you have a universal variable called "fish_greeting", then set fish_greeting will update that. Universal variables are stored by fish, persistently in a file, so doing that will update a file and change it in other running fish sessions too.

By adding "-g" (short for "--global"), you ensure that it only modifies a global variable (and shadowing the universal one if any in the current fish shell invocation only), creating it if necessary.

3
  • 2
    So set -g should always be used (in scripts at least) for global variables to remove the risk of a set var value changing a variable that happens to be universal (which could affect other scripts or interactive fish sessions by the same user)? Commented Mar 5 at 9:37
  • 2
    That's correct, yeah. It's good practice everywhere to explicitly specify the scope the first time you use a variable in a function. This includes config.fish, where we often see set -x foo bar, which should be set -gx foo bar. Commented Mar 5 at 10:32
  • 1
    Wow, changing variables stored in persistent memory with the same command used for changing mere local variables seems a bit of a misfeature. Contrast with e.g. Python, where you need to explicitly declare globals used in a function with global foo to modify them. Commented Mar 5 at 11:50

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.