[Short Tip] Output/redirect content to a file in Nushell

And another short tip about Nushell – I promise that those will be less frequent the more I get used to it.

My current problem was: how do I redirect content to a file like echo hello > foo.txt and echo world >> foo.txt? The typical approach didn’t work:

❯ echo "hello" > foo.txt
 0 │ hello   
 1 │ >       
 2 │ foo.txt 

Yeah, certainly not what I had in mind. Instead, I had to rethink the approach here. What is what we want to do here? First we output content and need to save it to a file. The connection is a pipe, as usual in Nushell:

❯ echo hello | save foo.txt
❯ open foo.txt

That worked! Second, we want to append something. So we need to open the file, append something, and save it again. In between all steps we need pipes – Nushell, after all:

❯ open foo.txt | append "world"| save --raw foo.txt
❯ open foo.txt

Note that save needs the --raw flag here: it tries to be smart to guess in what format we want to save it, and for some reason in my case it didn’t save the new lines without the flag.

And that’s it. It is not as short as I would like it to be compared to Bash and others. On the other hand it is way more flexible (it can also handle structured data this way like json) and it is not like I use redirection all the time.