2

What is the difference between filename=${1:-/etc/hosts} and filename=/etc/hosts?

For example:

filename=/etc/hosts

if [ -r "$filename" ] && [ -s "$filename" ]; then
    md5sum $filename
else
    echo "$filename cannot be processed"
fi

and

filename=${1:-/etc/hosts}

if [ -r "$filename" ] && [ -s "$filename" ]; then
    md5sum $filename
else
    echo "$filename cannot be processed"
fi
0

1 Answer 1

10

filename=${1:-/etc/hosts} assigns value /etc/hosts to variable filename if $1 is not set or null.

From GNU bash manual:

${parameter:-word}

If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.

4
  • Which is to say that unless first param $1 sent to it, it wiöl default to /etc/hosts
    – Petter H
    Jun 29, 2014 at 11:59
  • @PetterH: No, if you set $1 to null, /etc/hosts is assigned to filename.
    – cuonglm
    Jun 29, 2014 at 12:05
  • @PetterH: I mean, if you try: ./yourscript "" 2 3, filename is set to /etc/hosts even if you had pass $1 to script.
    – cuonglm
    Jun 29, 2014 at 12:23
  • Right you are! I did not concider that.
    – Petter H
    Jun 29, 2014 at 12:24

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