在没有 source 命令的情况下将 bash 脚本作为源运行
有没有办法将脚本标记为“作为源运行”,这样您就不必添加 source
或“.” 每次都命令它吗? 即,如果我编写一个名为“sup”的脚本,我想将其称为
sup Argument
而不是
source sup Argument
or
. sup Argument
基本上,我尝试在脚本中使用 cd 。
Is there any way to mark a script to be "run as source" so you don't have to add the source
or "." command to it every time? i.e., if I write a script called "sup", I'd like to call it as
sup Argument
rather than
source sup Argument
or
. sup Argument
Basically, I'm trying to use cd
within a script.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Bash 会在它或你的内核考虑它应该在其中做什么之前就分叉并启动一个子 shell。 这不是你可以“撤消”的事情。 所以不,这是不可能的。
值得庆幸的是。
相反,请查看 bash 函数:
将其放入您的 ~/.bashrc 中。
Bash forks and starts a subshell way before it or your kernel even considers what it's supposed to do in there. It's not something you can "undo". So no, it's impossible.
Thankfully.
Look into
bash
functions instead:Put that in your
~/.bashrc
.当您运行 shell 时,有两种方法可以调用 shell 脚本:
执行脚本会生成一个正在运行该脚本的新进程。 这是通过输入脚本名称来完成的,如果它是可执行的并且以
行,或者直接调用
获取脚本在其父 shell(即您正在其中输入命令的 shell)内运行它。 这是通过输入
或
因此,未获取源的 shell 脚本内的 cd 永远 不会传播到其父 shell,因为这会违反进程隔离。
如果您只对 cd 感兴趣,则可以使用 cd “快捷方式”删除该脚本...查看 bash 文档,在 CDPATH 环境变量中。
否则,您可以使用别名来键入单个命令,而不是 source 或 .:
When you are running a shell, there are two ways to invoke a shell script:
Executing a script spawns a new process inside which the script is running. This is done by typing the script name, if it is made executable and starts with a
line, or directly invoking
Sourcing a script runs it inside its parent shell (i.e. the one you are typing commands into). This is done by typing
or
So the cd inside a shell script that isn't sourced is never going to propagate to its parent shell, as this would violate process isolation.
If the cd is all you are interested about, you can get rid of the script by using cd "shortcuts"... Take a look into the bash doc, at the CDPATH env var.
Otherwise, you can use an alias to be able to type a single command, instead of source or .:
为它创建一个别名:
或者沿着这些思路。
另请参阅: 为什么 cd 在 bash 中不起作用shell 脚本?
通过反例回答评论:Solaris 10 上的 Korn Shell 实验表明我可以做到:
Solaris 10 上的 Bash (3.00.16) 实验也显示了相同的行为。
Create an alias for it:
Or along those lines.
See also: Why doesn't cd work in a bash shell script?
Answering comment by counter-example: experimentation with Korn Shell on Solaris 10 shows that I can do:
Experimentation with Bash (3.00.16) on Solaris 10 also shows the same behaviour.
如果您在调用时对脚本进行子 shell,则无法在当前环境中获取脚本。
但是,您可以检查脚本是否已获取,如果没有,则强制脚本终止:
同样,您可以强制不获取脚本,而是将其子化shelled 相反(保留当前的 shell 环境):
两个版本都可用作要点:请参阅请来源 和不要来源。
It is not possible to source a script in your current environment if you sub-shell the script at invoke.
However, you can check that script is sourced and force the script to terminate if not:
The same way, you can force a script not to be sourced but to be sub-shelled instead (preserve current shell environment):
Both versions are available as gists: see please source and don't source.