Edit shell script while it's running

前端 未结 11 1789
余生分开走
余生分开走 2020-11-27 03:18

Can you edit a shell script while it\'s running and have the changes affect the running script?

I\'m curious about the specific case of a csh script I have that batc

11条回答
  •  执笔经年
    2020-11-27 03:49

    Try this... create a file called bash-is-odd.sh:

    #!/bin/bash
    echo "echo yes i do odd things" >> bash-is-odd.sh
    

    That demonstrates that bash is, indeed, interpreting the script "as you go". Indeed, editing a long-running script has unpredictable results, inserting random characters etc. Why? Because bash reads from the last byte position, so editing shifts the location of the current character being read.

    Bash is, in a word, very, very unsafe because of this "feature". svn and rsync when used with bash scripts are particularly troubling, because by default they "merge" the results... editing in place. rsync has a mode that fixes this. svn and git do not.

    I present a solution. Create a file called /bin/bashx:

    #!/bin/bash
    source "$1"
    

    Now use #!/bin/bashx on your scripts and always run them with bashx instead of bash. This fixes the issue - you can safely rsync your scripts.

    Alternative (in-line) solution proposed/tested by @AF7:

    {
       # your script
    } 
    exit $?
    

    Curly braces protect against edits, and exit protects against appends. Of course, we'd all be much better off if bash came with an option, like -w (whole file), or something that did this.

提交回复
热议问题