21

What is the fish shell equivalent to the following bash:

echo ${TEST:-1}

In bash this would print the value of TEST if there was one, or 1 if there was not.

1

2 Answers 2

15

I believe you need temponary variable (or a function). If $TEST doesn't exist, it's expanded to nothing, and $test_or only contains 1. It would be nice to have real way of doing that, but currently the syntax is issue, and it doesn't appear it's really needed for most purposes.

set test_or $TEST 1
echo $test_or[1]

Also, if all you want is to modify $TEST if it doesn't exist already, you can use set -q.

set -q TEST; or set TEST 1
echo $TEST
8

To reference a variable and provide a default value in-line you can use command substitution containing a conditional which does echo on both branches.

> echo (if set -q someVar; echo $someVar; else; echo 'a default value'; end)
a default value
> set someVar 42
> echo (if set -q someVar; echo $someVar; else; echo 'a default value'; end)
42

Since this is kind of verbose, you could initialize the variable on a different line when it is unset.

> echo $otherVar

> set -q otherVar; or set otherVar 'a default value'
> echo $otherVar
a default value

If you really want the ability to substitute a default in-line, you can do it in a function using indirection, and then call that function.

> function orDefault
      set -q $argv[1]; and echo $$argv[1]; or echo $argv[2]
  end
>
> echo $moreVar

> echo (orDefault moreVar 'a default value')
a default value
> set moreVar 42
> echo (orDefault moreVar 'a default value')
42

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .