views:

41

answers:

2

Ok, I can't figure this out from reading Perl's documentation. I'm looking at the RHEL4 init script for Apache... What does this line of code do?

httpd=${HTTPD-/usr/sbin/httpd}

Why not just httpd=/usr/sbin/httpd? What's up with all the extra syntax?

-Geoffrey Lee

+5  A: 

That's not Perl, its shell. Init scripts are usually written in shell. Specifically it means "if defined, use the HTTPD environment variable, otherwise use /usr/sbin/httpd".

Look here for more info.

Schwern
do you think OP has a typo error? should it be $HTTPD:- instead of just -
ghostdog74
`${VAR-default}` works, though its not the documented bash way to do it. I can't say more, I'm not much of a shell programmer.
Schwern
It certainly is documented: look for the section "Paramater Expansion" in the man page.
glenn jackman
@glenn I did. I even linked to it. Look closely, the documented version is `${VAR:-default}` where the OP is using `${VAR-default}`. Note the lack of a colon. Maybe somewhere its documented that the colon is optional, but its not immediately obvious from the docs.
Schwern
@Schwern: It's documented in the man page in the sentence immediately preceding the section about `${VAR:-default}` as you can see in my answer. "Omitting the colon..." It's worded a little differently in the reference you linked to, but it's in the same place. It **is** easy to miss (I did for a long time).
Dennis Williamson
@Dennis Yep. I missed it because I was searching for `:` and skimming the list of parameter styles.
Schwern
+2  A: 

The colon affects whether the variable is checked for being unset or null versus only checking for whether it's unset.

$ var="goodbye"; echo ${var-hello}
goodbye
$ var="goodbye"; echo ${var:-hello}
goodbye
$ var= ; echo ${var:-hello}
hello
$ var= ; echo ${var-hello}    # var is null, only test for unset so no sub. made

$ unset var; echo ${var:-hello}
hello
$ unset var; echo ${var-hello}
hello

From the Bash man page:

       When not performing substring expansion,  using  the  forms  documented
       below,  bash tests for a parameter that is unset or null.  Omitting the
       colon results in a test only for a parameter that is unset.

       ${parameter:-word}
              Use Default Values.  If parameter is unset or null,  the  expan‐
              sion  of word is substituted.  Otherwise, the value of parameter
              is substituted.
Dennis Williamson