运行脚本bash函数 [英] A bash function that runs script
问题描述
我想编写一个名为bash函数 myrun
,这样,这样做
myrun script.py
用Python文件:
#MYRUN:nohup的蟒蛇-u script.py&安培;进口时间
打印世界,你好
time.sleep(2)
打印再次
将运行脚本的在文件的第一行指定的命令,就在 #MYRUN:
我应该在的.bashrc
插入允许这样这是我现在有:
myrun(){
[$ 1=]]&放大器;&安培;回声用法:myrun python_script.py&放大器;&安培;返回0
<东西在这里的awk或别的东西&GT?;
}
一个简约版:
$函数myrun {
[$ 1=]]&放大器;&安培;回声用法:myrun python_script.py&放大器;&安培;返回
当地CMD = $(头-n 1<$ 1| sed的S'/#* MYRUN://)
$ CMD
}$ myrun script.py
追加输出的nohup.out
$猫的nohup.out
你好,世界
再来一次
$
(这不是很清楚,我不管你是最好使用的eval$ CMD
或只是 $ CMD
在函数的最后一行,但如果你想以包括&放大器;在MYCMD指令,那么 $ CMD
更简单)
使用一些基本的检查:
功能myrun {
[$ 1=]]&放大器;&安培;回声用法:myrun python_script.py&放大器;&安培;返回
当地CMD = $(头-n 1<$ 1)
如果[[$ CMD =〜^#MYRUN:]];然后CMD = $ {#CMD#MYRUN:'}
其他回声myrun:#MYRUN:头部未找到>&放大器; 2;假;返回;科幻
如果[[-z $ CMD]];然后回声myrun:没有指定命令>&放大器; 2;假;返回;科幻
$#CMD或EVAL$ CMD如果你preFER
}
I'm trying to write a bash function named myrun
, such that doing
myrun script.py
with a Python file:
#MYRUN:nohup python -u script.py &
import time
print 'Hello world'
time.sleep(2)
print 'Once again'
will run the script with the command specified in the first line of the file, just after #MYRUN:
.
What should I insert in .bashrc
to allow this? Here is what I have now:
myrun () {
[[ "$1" = "" ]] && echo "usage: myrun python_script.py" && return 0
<something with awk here or something else?>
}
A minimalist version:
$ function myrun {
[[ "$1" = "" ]] && echo "usage: myrun python_script.py" && return
local cmd=$(head -n 1 < "$1" | sed s'/# *MYRUN://')
$cmd
}
$ myrun script.py
appending output to nohup.out
$ cat nohup.out
Hello world
Once again
$
(It's not clear to me whether you're better off using eval "$cmd"
or simply $cmd
in the last line of the function, but if you want to include the "&" in the MYCMD directive, then $cmd
is simpler.)
With some basic checking:
function myrun {
[[ "$1" = "" ]] && echo "usage: myrun python_script.py" && return
local cmd=$(head -n 1 <"$1")
if [[ $cmd =~ ^#MYRUN: ]] ; then cmd=${cmd#'#MYRUN:'}
else echo "myrun: #MYRUN: header not found" >&2 ; false; return ; fi
if [[ -z $cmd ]] ; then echo "myrun: no command specified" >&2 ; false; return; fi
$cmd # or eval "$cmd" if you prefer
}
这篇关于运行脚本bash函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!