0

I need some help from you guys to understand this black of code. I am having a problem with the last line.

thanks

    default_ip=$(hostname -I)   //display localhost ip?
    printf Put your local IP    //print statement
    read ip                     //save input to $ip
    ip="${ip:-${default_ip}}"   //not sure what is this, can you help?

thank you

Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • The bash man page has this.. ` ${parameter:-word} Use Default Values. If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted ` – Matthew Hannigan Sep 21 '19 at 06:08

1 Answers1

1

First: // is not a comment marker in shell syntax; use #. Please be very careful about trying to use other language's syntax in the shell, as it's often different. Here is an example where this exact mistake led to an erased server.

Now, to the script:

default_ip=$(hostname -I)

hostname -I prints all IP addresses for the computer (separated by spaces). $() runs the contents as a command, and captures that output. The default_ip= part assigns that output to the default_ip variable. hostname -I prints all IP addresses for the computer (separated by spaces), so that's what default_ip gets set to.

printf Put your local IP

This doesn't work right. Are there supposed to be quotes around the Put your local IP part? Anyway, printf prints things, but it's kind of complicated to use right, so I'll just duck that part of the question.

read ip

Reads something from standard input (the terminal, by default), and stores it in the ip variable.

ip="${ip:-${default_ip}}"

Uses the variable default_ip as a default value for the ip variable. The ${thing1:-thing2} syntax tries to get the value of the variable thing1, but if it isn't defined as a variable or is defined as the empty string it uses the string thing2 instead. In this case, thing2 is ${default_ip}, which gets the value of the variable default_ip.

Basically, this means that if the user just hits return instead of entering an IP address, it uses the output from hostname -I instead.

Gordon Davisson
  • 118,432
  • 16
  • 123
  • 151