[英]Terminal closes when I source my script (run with dot at the start)
Here is my code:这是我的代码:
#!/bin/bash
if [[ $1 = "" ]]; then
exit 0
fi
array=($(cat $1))
let b=${#array[@]}-1
count=0
for i in {1..7}; do
for j in {30..37}; do
for n in {40..47}; do
if [[ $count -gt $b ]]; then
printf '\n'
printf '\e[0m'
exit 1
fi
printf '\e[%s;%s;%sm%-5s' "$i" "$j" "$n" "${array[$count]}"
printf '\e[0m'
let count=$count+1
done
printf '\n'
done
done
#printf '\n'
printf '\e[0m'
exit 0
The problem is that when I start it like this问题是当我这样开始时
. color.sh arg
or without argument, it just closes.或者没有争论,它只是关闭。 I know that the reason for that is
exit
.我知道原因是
exit
。 Is there any way correct my code so I could start a script with dot at start and terminal wouldn't close after execution?有什么方法可以更正我的代码,这样我就可以在开始时用点启动一个脚本,而终端在执行后不会关闭? I don't want to start it like this:
./script
我不想这样开始:
./script
Replace all exit
with return
.用
return
替换所有exit
。 return
inside a sourced script will even work with exit codes:在源脚本中
return
甚至可以使用退出代码:
$ . <(echo "echo before; return 0; echo after")
before
$ echo $?
0
$ . <(echo "echo before; return 7; echo after")
before
$ echo $?
7
When you use the dot to run a script you are "sourcing" it, which means the interpreter reads and executes all the commands in that script in the context of the current environment without spawning a subshell, as if you had typed each yourself.当您使用点来运行脚本时,您是在“采购”它,这意味着解释器在当前环境的上下文中读取并执行该脚本中的所有命令,而不产生子shell,就好像您自己键入了每个命令一样。
That's why if you source it you can set variables in a script that will remain after it has run, whereas running it in a subshell would encapsulate them, and they would go away when the script ends.这就是为什么如果你获取它,你可以在脚本中设置变量,在它运行后会保留,而在子shell中运行它会封装它们,当脚本结束时它们会消失。
Accordingly, if you source a script that hits an exit
, it causes the calling environment to exit.因此,如果您获取一个点击
exit
的脚本,它会导致调用环境退出。 Use return as Socowi suggested.按照Socowi 的建议使用 return。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.