0

I spent some time building this handy bash script that accepts input via stdin. I got the idea from the top answer to this question: Pipe input into a script

However, I did something really dumb. I typed the following into the terminal:

echo '{"test": 1}' > ./myscript.sh

I meant to pipe it | to my script instead of redirecting > the output of echo.

Up until this point in my life, I never accidentally clobbered any file in this manner. I'm honestly surprised that it took me until today to make this mistake. :D

At any rate, now I've made myself paranoid that I'll do this again. Aside from marking the script as read-only or making backup copies of it, is there anything else I can do to protect myself? Is it a bad practice in the first place to write a script that accepts input from stdin?

Tim Reddy
  • 4,340
  • 1
  • 40
  • 77
  • 2
    What about using `set -o noclobber`? – PesaThe Jul 18 '18 at 19:18
  • I'd argue that the correct answer is to have a good backup system in place -- not just for scripts, but for *everything* you don't want to randomly lose. You can certainly protect against individual types of data loss mistakes, but not against all of them. – Gordon Davisson Jul 18 '18 at 19:25
  • My question is probably too broad given the variety of answers. I've picked the answer I implemented because I do have version control and a backup plan, but I never thought to toss the scripts in a directory on the path. – Tim Reddy Jul 19 '18 at 12:48

2 Answers2

3

Yes, there is one thing you can do -- check your scripts into a source-code-control repository (git, svn, etc).

bash scripts are code, and any non-trivial code you write should be checked in to source-code-control (and changes committed regularly) so that when something like this happens, you can just restore the most-recently-committed version of the file and continue onwards.

Jeremy Friesner
  • 70,199
  • 15
  • 131
  • 234
2

This is a very open-ended question, but I usually put scripts in a global bin folder (~/.bin or so). This lets me invoke them as myscript rather than path/to/myscript.sh, so if I accidentally used > instead of |, it'd just create a file by that name in the current directory - which is virtually never ~/.bin.

Siguza
  • 21,155
  • 6
  • 52
  • 89
  • Yes the root of my problem, aside from the `>`, is I ran the script in the current directory. Your technique will definitely help. Executing the bash script without the extension is a bonus in this case! – Tim Reddy Jul 18 '18 at 19:01