1

Maybe I am searching wrong, but I cannot find any solution for this...

I want to use a shell script to append the following to my bashrc file (to make the installation of Windows Subsystem for Linux easier):

# Load X display (run 'XLaunch' on Windows with 'Disable access control' checked and 'Native opengl' unchecked!)
# https://sourceforge.net/projects/vcxsrv/
export DISPLAY=$(grep -m 1 nameserver /etc/resolv.conf | awk '{print $2}'):0.0

This is my script.sh:

### Add useful stuff to bashrc
### --------------------------
echo "
# Load X display (run 'XLaunch' on Windows with 'Disable access control' checked and 'Native opengl' unchecked!)
# https://sourceforge.net/projects/vcxsrv/
export DISPLAY=$(grep -m 1 nameserver /etc/resolv.conf | awk '{print $2}'):0.0
" >> ~/.bashrc

This is what is appended to bashrc when running script.sh:

# Load X display (run 'XLaunch' on Windows with 'Disable access control' checked and 'Native opengl' unchecked!)
# https://sourceforge.net/projects/vcxsrv/
export DISPLAY=172.19.96.1:0.0

Since my IP may change, I want to append the raw command itself to bashrc, not the output of the command. I am sure this must be a duplicate question, but I cannot find a useful answer. There are just to many answers that simply refer to echo or cat. cat yields the same undesired result:

cat <<EOF >> ~/.bashrc
# Load X display (run 'XLaunch' on Windows with 'Disable access control' checked and 'Native opengl' unchecked!)
# https://sourceforge.net/projects/vcxsrv/
export DISPLAY=$(grep -m 1 nameserver /etc/resolv.conf | awk '{print $2}'):0.0
EOF
Azrael_DD
  • 171
  • 9

1 Answers1

2

The issue is using double quote/ticks vs single quote/ticks

Try to reverse the use of " and ', as " will interpret and run the command and ' will not interpret or run it.

This should work:

echo 'export DISPLAY=$(grep -m 1 nameserver script.sh | awk '\''{print $2}'\''):0.0' >> temp.txt

$ cat temp.txt
export DISPLAY=$(grep -m 1 nameserver /etc/resolv.conf | awk '{print $2}'):0.0

Reference: https://www.howtogeek.com/howto/29980/whats-the-difference-between-single-and-double-quotes-in-the-bash-shell/

Reference to escaping text inside a quoted string: https://stackoverflow.com/a/48352047/13064727

Donald S
  • 1,583
  • 1
  • 10
  • 26
  • @GordonDavisson, you are correct, thanks for pointing that out. I modified the answer to include usage of escaping a single quote inside. Should work correctly now – Donald S Jul 13 '20 at 10:40