0

I am new to coding and already found a few topics about this on stackoverflow, but couldn't make it work, as they seem overextended to me. I might need some guidance.

I need to change some variables in an external bash script 'comlink.conf'. But only specific ones. Others should be left like they are.

ready=0
test=1
new=2

echo 'ready='$ready > comlink.conf
sleep 10

ready=1

echo 'ready='$ready > comlink.conf

If I do it like that, 'test=1' and 'new=2' will be overwritten completely and are gone from the file. That should not happen.

What would be the most easiest way to do this?

3
  • when you use > in echo it overwrites the content in comlink.conf. If you want to add data you could use >>. Commented Aug 11, 2017 at 11:50
  • Great idea! But then 'ready' is 0 and in the next line it is 1. I need to update the specific variable, not add the same again with a different value, because another script will read and use the variables in that file. Commented Aug 11, 2017 at 11:55
  • You should look at a tool like sed for something like this Commented Aug 11, 2017 at 11:55

2 Answers 2

1

You can use sed with a different substitution like:

sed 's/ready=.*/ready=1/' comlink.conf > tmp
mv tmp comlink.conf

or if you are using GNU sed:

sed -i 's/ready=.*/ready=1/' comlink.conf

or BSD sed:

sed -i'' 's/ready=.*/ready=1/' comlink.conf
Sign up to request clarification or add additional context in comments.

4 Comments

That works perfectly. Thank you!!! But why is it only working with a temp file? Is it not possible to edit an external file directly?
@daniel_e the versions of sed with -i support will modify it in-place. If you try to use redirection though, you'll end up truncating the file before reading it, so you need a temp file (or something that works like it)
Perfect. Thanks for the info, Eric. Now I learned something. :-)
@daniel_e to be honest, the -i options do a temp file solution too instead of directly in place (which can matter if you have a full disk for example). If you need real in place editing you can use a tool like ed
1

If I understand you right, you want to replace a line in a file. You shouldn't use echo for that.

Instead I would suggest using sed:

sed '/.*ready*/s/.*/ready=1/' comlink.conf

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.