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
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 .
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.
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.
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.
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.
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With