Ale*_*lex 7 shell bash function
我知道这set -e是我的朋友,以便在出错时退出。但是如果脚本是源代码怎么办,例如从控制台执行一个函数?我不想在错误时关闭控制台,我只想停止脚本并显示错误消息。
我需要检查$吗?手动执行每个命令以使其成为可能?
这是一个myScript.sh显示问题的示例脚本:
#!/bin/sh
set -e
copySomeStuff()
{
source="$1"
dest="$2"
cp -rt "$source" "$dest"
return 0
}
installStuff()
{
dest="$1"
copySomeStuff dir1 "$dest"
copySomeStuff dir2 "$dest"
copySomeStuff nonExistingDirectory "$dest"
}
Run Code Online (Sandbox Code Playgroud)
该脚本是这样使用的:
$ source myScript.sh
$ installStuff
Run Code Online (Sandbox Code Playgroud)
这只会关闭控制台。显示的错误cp丢失。
我建议您将一个脚本作为子 shell 运行,可能会采购一个文件来读取函数定义。让该脚本errexit为自己设置shell 选项。
当您source从命令行使用时,“脚本”实际上是您的交互式 shell。退出意味着终止 shell 会话。可能有解决此问题的方法,但如果您想设置errexit会话,最好的选择就是:
#!/bin/bash
set -o errexit
source file_with_functions
do_things_using_functions
Run Code Online (Sandbox Code Playgroud)
额外的好处:不会污染交互会话的功能。