可自行编辑的Bash脚本 [英] Bash script that edits itself

查看:50
本文介绍了可自行编辑的Bash脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个可以自行编辑的bash脚本.我要使用的代码行是:

I'm trying to write a bash script that can edit itself. The line of code I'm trying to use is:

sed "s/$STRING_TO_REPLACE/$NEW_STRING/" < $0 > $0

但是运行脚本后,我最终得到一个空文件.有什么建议吗?

But after running the script I end up with an empty file. Any suggestions?

我正在创建一个包含两个包含默认值的变量的脚本.唯一的问题是,对于使用该默认值的许多工作站,这些默认值将有所不同.我希望运行这些工作站的人员都不需要自己打开脚本并编辑默认值,因此我想在脚本中包含更改默认值的功能.我的要求之一是脚本必须是自包含的.脚本中不应包含其他文件,并且环境变量也应没有.这将要求脚本能够进行自我编辑.

I am creating a script that has two variables that contain default values. The only problem is, these default values will be different for each of the many stations where it will be used. I would rather none of the people running these stations had to open the script and edit the defaults themselves, so I want to include the ability to change the defaults in the script. One of the requirements I have is that the script must be self contained; no other files are to accompany the script and there are to be no environment variables. This would require the script to be able to edit itself.

推荐答案

如果要使用sed进行就地替换,请使用 -i 开关.

If you want to do an in-place substitution with sed, use the -i switch.

我不建议即时重写当前正在执行的脚本.我不确定是否可以,但是如果可以的话,维护代码肯定很有趣(阅读:困难):-)

I wouldn't recommend re-writing the currently executing script on the fly. I'm not sure whether it's possible or not, but if it is, it would certainly be interesting (read: difficult) code to maintain :-)

这篇关于可自行编辑的Bash脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆