Search code examples
bashshellcommandparameter-expansion

How to understand this "bash" shell command


The command is:

[ -d $x ] && echo $x | grep "${1:-.*}"

I have run it separately, and [ -d $x ] && echo $x just outputs the directory name. What does the ${1:-.*} mean?


Solution

  • In the script you refer to, grep is called. Its first argument, what it will search for, is either the first script parameter $1, if one was given, or .*, which matches anything, if no parameters were given.

    "$1" or "${1}" in a bash script is replaced with the first argument the script was called with. Sometimes it's necessary to process that string a little, which can be done with shell parameter expansion, as Etan Reisner helpfully pointed out. :- is one such tool; there are several others.

    "${1:-.*}" means "if parameter 1 is unset or null (i.e., no such parameter was given), then substitute the part after :; in this case, .*.

    Example script pe:

    #!/bin/bash
    printf 'parameter count = %d\n' $#
    printf 'parameter 1 is "%s"\n' "$1"
    printf 'parameter 1 is "%s"\n' "${1:-(not given)}"
    

    Output:

    $ ./pe 'foo bar'
    parameter count = 1
    parameter 1 is "foo bar"
    parameter 1 is "foo bar"
    
    $ ./pe
    parameter count = 0
    parameter 1 is ""
    parameter 1 is "(not given)"