Home > other >  Bash: How to edit a file onto/into itself - without using a secondary file
Bash: How to edit a file onto/into itself - without using a secondary file

Time:06-25

Note: I am particularly looking for a coding hack, not for an alternative solution. I am aware that awk, sed etc. can do this inline edit just fine.

$ echo '1' > test
$ cat test > test
$ cat test
$ 

Is there a way, to somehow make the second command output the original contents (1 in this case)? Again, I am looking for a hack which will work without using a secondary file. Another question on this forum solely focused on alternative solutions which is not what I am looking for.

CodePudding user response:

You can store the content in a shell variable rather than a file.

var=$(<test)
printf "%s\n" "$var" > test

Note that this might only work for text files, not binary files. If you need to deal with them you can use encoding/decoding commands in the pipeline.

You can't do it without storing the data somewhere. When you redirect output to a file, the shell truncates the file immediately. If you use a pipeline, the commands in the pipeline run concurrently with the shell, and it's unpredictable which will run first -- the shell truncating the file or the command that tries to read from it.

CodePudding user response:

With thanks to the comment made by @Cyrus to the original question

$ sudo apt install moreutils
$ echo '1' > test
$ cat test | sponge test
$ cat test
1

It does require installing an extra package and pre-checking for the binary using something like where sponge to check if it is installed.

  • Related