Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In fish shell, how to set a variable with default fallback?

I'm looking for the equivalent of the following bash syntax, but for the fish shell:

local datafile="${_Z_DATA:-$HOME/.z}"

i.e define a local variable that will take the value of $_Z_DATA if this one is define, or else will take the value of $HOME/.z

like image 770
Nicolas C Avatar asked Feb 04 '19 21:02

Nicolas C


People also ask

How do you set a variable in a fish shell?

To give a variable to an external command, it needs to be “exported”. Unlike other shells, fish does not have an export command. Instead, a variable is exported via an option to set , either --export or just -x .

How do I set my default fish shell?

Switching to fish? If you wish to use fish (or any other shell) as your default shell, you need to enter your new shell's executable /usr/local/bin/fish in two places: add /usr/local/bin/fish to /etc/shells. change your default shell with chsh -s to /usr/local/bin/fish.

How do I set a variable in fish shell?

Unlike other shells, fish has no dedicated VARIABLE=VALUE syntax for setting variables. Instead it has an ordinary command: set, which takes a variable name, and then its value.

How do I change the default location of the fish shell?

Change your default shell with: This assumes you installed fish to /usr/local/bin, which is the default location when you've compiled it yourself. If you installed it with a package manager, the usual location is /usr/bin/fish, but package managers typically already add it to /etc/shells. Just substitute the correct location.

How to create functions and variables in fish?

Fish starts by executing commands in ~/.config/fish/config.fish. You can create it if it does not exist. It is possible to directly create functions and variables in config.fish file, using the commands shown above. For example: However, it is more common and efficient to use autoloading functions and universal variables.

How does set work in shell script?

set manipulates shell variables. If both a variable name and values are provided, set assigns the values to the variable of that name. Because all variables in fish are lists, multiple values are allowed. If only a variable name has been given, set sets the variable to the empty list.


1 Answers

As far as I know, there is no syntax for this; you need something like

set datafile "$_Z_DATA"
test -z "$datafile"; and set datafile "$HOME/.z"

or

if set -q _Z_DATA; and test -n _Z_DATA
  set datafile "$_Z_DATA"
else
  set datafile "$HOME/.z"
fi

Unlike bash, variables defined inside a function are automatically local to that function, so no equivalent to local is needed. (A previous version of this answer used the -l option to localize the variable, but that makes it local to whatever block set occurs in.)

like image 185
chepner Avatar answered Oct 10 '22 10:10

chepner