1

I'm struggling getting this done. I need to run some commands on my current shell session (no script) and I want to redefine/reset a variable that was defined earlier, but it does not work, see below pls:

# server=`grep "<address>" /etc/file.conf |sed "s/<address>//"`
# echo $server
10.10.10.10

# [ "${server}" == "10.10.10.10" ] && ( sed -i "s/10.10.10.10/10.10.10.20/" /etc/file.conf ; server=10.10.10.20 ; echo $server)
10.10.10.20
# echo $server
10.10.10.10

the variable server does not take from inside of the &&

I've tried export, set, but no way to make this happen. The solution I found was to run the grep command again, but I'm so picky that I'd like to make this happen based on my first thought.

Any ideas?

Thanks!

the-burgh
  • 39
  • 4
  • 7
    The `( )` makes that part run in a subshell, which has a copy of the shell variable, but changing the copy doesn't change the original (the parent shell's copy of the variable). This is one of many reasons to use `if ... then ... fi` instead of faking it with `&&`. If you do need to use grouping, use `{ ... ; }` instead of `( )`. – Gordon Davisson Jun 02 '22 at 03:03
  • thanks @gordon-davisson ! The { ... ; } did the trick! One last thing for my knowledge, what are other scenarios that better fit/difference of ( ) and { } ? – the-burgh Jun 02 '22 at 13:12
  • 1
    Subshells are usually more annoying and confusing (and slow) than anything else (see ["Why avoid subshells?"](https://stackoverflow.com/questions/21976606)), so people generally try to avoid them. The main place there're useful is when you need to make changes to the shell state that'd need to be undone later; making the changes in a subshell prevents them from affecting the rest of the script (`cd`ing somewhere is a common example). See kojiro's answer [here](https://stackoverflow.com/questions/27801932) and Ivan's answer [here](https://stackoverflow.com/questions/60337745). – Gordon Davisson Jun 02 '22 at 17:55

0 Answers0