Search code examples
bashshellsh

Variable substitution with conditions


I am trying to do variable substitution depending on some conditions.

I have two variables, act_nic and con_name.

The act_nic variable always has some value (not empty) but the value of con_name may be null or sometimes it may have a value.

I have multiple commands like below,

nmcli connection modify ${act_nic} ipv6.never-default yes

In the place of act_nic, if con_name is not null then it should take the con_name value in the place of act_nic.

I have tried

${con_name:-act_nic}

The above will produce act_nic as a plain string, but it's not taking the actual value of the variable act_nic.

I have other ways where I can check if con_name is not null then set act_nic=$con_name, but I do not want to do this in that way as the value of act_nic is used elsewhere in the script, too.

I am trying to do this in single line. I'm using RHEL if it makes a difference.


Solution

  • Like you discovered, the string after :- is just static. To put a variable's expansion there, use the regular variable expansion syntax.

    ${con_name:-$act_nic}
    

    As a general guideline, probably add quoting if the values are not guaranteed to only consist of characters which have no special meaning to the shell; see also When to wrap quotes around a shell variable