What is the difference between ${hi:-bye} and ${hi:=bye}?

Study for the OSCP Linux Exam. Use our flashcards and multiple-choice questions to test your skills. Each query comes with detailed hints and explanations to enhance your preparedness. Get ready to conquer the exam!

Multiple Choice

What is the difference between ${hi:-bye} and ${hi:=bye}?

Explanation:
In Bash, how a default value is handled in parameter expansion depends on the operator you use. ${hi:-bye} provides a default when the variable is unset or empty, but it does not change the variable itself. It’s a non-destructive fallback: you get hi’s value if it exists and is not empty; otherwise you get bye, but hi stays as it was. ${hi:=bye} also uses a default when the variable is unset or empty, but it goes further by assigning that default to the variable. After this expansion, hi will hold bye, and any subsequent use of hi will see that value. Quick examples to illustrate: - If hi is unset: - echo ${hi:-bye} → prints bye; hi remains unset. - echo ${hi:=bye} → prints bye; hi becomes bye. - If hi already has a value (e.g., hi=hello): - echo ${hi:-bye} → prints hello; hi stays hello. - echo ${hi:=bye} → prints hello; hi remains hello. - If hi is an empty string (hi=""): - echo ${hi:-bye} → prints bye; hi remains empty. - echo ${hi:=bye} → prints bye; hi becomes bye. So the difference is that the first form only substitutes a default for output, while the second form also assigns that default to the variable when it’s unset or empty.

In Bash, how a default value is handled in parameter expansion depends on the operator you use.

${hi:-bye} provides a default when the variable is unset or empty, but it does not change the variable itself. It’s a non-destructive fallback: you get hi’s value if it exists and is not empty; otherwise you get bye, but hi stays as it was.

${hi:=bye} also uses a default when the variable is unset or empty, but it goes further by assigning that default to the variable. After this expansion, hi will hold bye, and any subsequent use of hi will see that value.

Quick examples to illustrate:

  • If hi is unset:

  • echo ${hi:-bye} → prints bye; hi remains unset.

  • echo ${hi:=bye} → prints bye; hi becomes bye.

  • If hi already has a value (e.g., hi=hello):

  • echo ${hi:-bye} → prints hello; hi stays hello.

  • echo ${hi:=bye} → prints hello; hi remains hello.

  • If hi is an empty string (hi=""):

  • echo ${hi:-bye} → prints bye; hi remains empty.

  • echo ${hi:=bye} → prints bye; hi becomes bye.

So the difference is that the first form only substitutes a default for output, while the second form also assigns that default to the variable when it’s unset or empty.

Subscribe

Get the latest from Passetra

You can unsubscribe at any time. Read our privacy policy