6

I have this script I'm basing my current script off of. I just don't understand why he has typeset result part dir=${1-$PWD} in there.

I get the same result if I just write dir=$PWD. With typeset is ${1-$PWD} changing how dir is set vs $PWD?

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
ZeroPhase
  • 383
  • 3
  • 16
  • 2
    There's a question for every possible variation of this particular form of parameter expansion... [What does this line in bash do? Parameter-||scriptname](https://unix.stackexchange.com/q/236631), or [Bourne shell: trailing `-` operator in parameter substitution](https://unix.stackexchange.com/q/191873), or [Using “${a:-b}” for variable assignment in scripts](https://unix.stackexchange.com/q/122845) etc... – don_crissti Oct 27 '17 at 20:53
  • I'll just link the relevant section of the standard here, too. There's a nice table describing the `${var*word}` expansions (for different values of `*`): http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02 – ilkkachu Oct 28 '17 at 09:13

3 Answers3

8

That's not brace expansion, that's a standard parameter expansion operator (dates back to the Bourne shell in the 70s).

${1-$PWD}

Expands to the value of $1 (the first positional parameter) if it is set (if $# is strictly greater than 0) even to the empty string, or to the content of the $PWD variable otherwise.

Run:

info zsh 'Parameter Expansion'

for details.

typeset is not Bourne nor POSIX, but it's not zsh-specific either. It comes from the Korn shell (from the early 80s) and is used to limit the scope of a variable to the current function. It's also found in bash and yash.

Run:

info zsh typeset

for details.

Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
6

${1-$PWD} is a shell parameter expansion pattern.

It is used to expand to a default value based on another -- whatever on the right of -. Here, in your case:

  • If $1 is unset, then the expansion of $PWD would be substituted

  • Otherwise i.e. if $1 is set to any value (including null), its value would be used as the result of expansion

Example:

% echo "Foo${1-$PWD}"   
Foo/home/bar

% set -- Spam

% echo "Foo${1-$PWD}"
FooSpam
Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
heemayl
  • 54,820
  • 8
  • 124
  • 141
4

It tests $1 for a value, using that before $PWD.

Ignacio Vazquez-Abrams
  • 44,857
  • 7
  • 93
  • 100