Search code examples
zshvariable-substitution

Is there a parameter substitution syntax for file or directory existence?


I would like to use parameter substitution to compute a path based on

  1. a variable being defined
  2. a first default directory to be used if it exists
  3. a file inside the $HOME directory to be used if neither of 1 or 2 are available.

The variable (#1) and the file in $HOME (#3) are easy:

${KEEPER_HOME:-$HOME/.keeper}

But is there a parameter/variable substitution syntax in Zsh for #2? If we imagined that || did this, I would be looking for something like this:

${KEEPER_HOME:-$HOME/.config/keeper||$HOME/.keeper}

Of course I can do it with test inside $(...) but I am hoping that something more concise and readable exists.


Solution

  • This only uses parameter expansions, but it's two lines:

    glob=($HOME/.config/keeper(N/))
    result=${KEEPER_HOME:-${glob:-$HOME/.keeper}}
    

    The glob= line uses the / glob qualifier to check for the directory. The N qualifier turns on nullglob, so the variable will be empty if the directory doesn't exist.

    There may be a way to move the globbing into the nested parameter expansion, but I haven't found one yet.