如何最好地包括其他脚本? [英] How best to include other scripts?

查看:50
本文介绍了如何最好地包括其他脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常包含脚本的方式是使用源代码"

The way you would normally include a script is with "source"

例如:

main.sh:

#!/bin/bash

source incl.sh

echo "The main script"

incl.sh:

echo "The included script"

执行"./main.sh"的输出为:

The output of executing "./main.sh" is:

The included script
The main script

...现在,如果您尝试从其他位置执行该Shell脚本,除非包含在您的路径中,否则它将找不到包含.

... Now, if you attempt to execute that shell script from another location, it can't find the include unless it's in your path.

确保脚本能够找到包含脚本的好方法是什么,特别是例如在脚本需要可移植的情况下?

What's a good way to ensure that your script can find the include script, especially if for instance, the script needs to be portable?

推荐答案

我倾向于使我的所有脚本彼此相对. 这样我可以使用dirname:

I tend to make my scripts all be relative to one another. That way I can use dirname:

#!/bin/sh

my_dir="$(dirname "$0")"

"$my_dir/other_script.sh"

这篇关于如何最好地包括其他脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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