1

I have a bash script and want to write something in it for use in the next time:

#this get the full path of the script
SCRIPT="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )/$(basename $0)"

NUMBER=10

#This change only in the first occurrence 
cat "$SCRIPT" | sed "1,/NUMBER=../s/NUMBER=../NUMBER=$((NUMBER + 1))/" > "$SCRIPT"

The problem I am having is that it produce an empty file. Can I overwrite my bash script in your own code?

1

2 Answers 2

4
cat "$SCRIPT" | ... > "$SCRIPT"

Don't do this. It will only lead to pain and suffering. And don't write self-modifying code at all if you can help it. But if you must, write to a temporary file first and rename after.

Sign up to request clarification or add additional context in comments.

Comments

1

Using temp file can save the situation:

#this get the full path of the script
SCRIPT="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )/$(basename $0)"

NUMBER=10

#This change only in the first occurrence 
sed "1,/NUMBER=../s/NUMBER=../NUMBER=$((NUMBER + 1))/" "$SCRIPT" > temp.tmp
cat temp.tmp > "$SCRIPT"
rm temp.tmp

But it's really interesting if there's a way to solve the problem without temp file:)

4 Comments

cat "$SCRIPT" | sed "1,/NUMBER=../s/NUMBER=../NUMBER=$((NUMBER + 1))/" | sponge "$SCRIPT" (command sponge from moreutils)
All these Useless Uses of Cats!
Right, you don't need the invocation of cat. Sorry for that.
It's not our's, it was copied from the topicstarter's message:)

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.