将bash脚本作为源而不使用源命令运行

typ*_*ror 20 bash

有没有办法将脚本标记为"作为源运行",因此您不必添加source或"." 每次命令它?也就是说,如果我写一个名为"sup"的脚本,我想称之为

sup Argument
Run Code Online (Sandbox Code Playgroud)

而不是

source sup Argument
Run Code Online (Sandbox Code Playgroud)

要么

. sup Argument
Run Code Online (Sandbox Code Playgroud)

基本上,我正在尝试cd在脚本中使用.

lhu*_*ath 32

Bash在它或你的内核甚至考虑它应该在那里做什么之前分叉和星球.这不是你可以"撤消"的东西.所以不,这是不可能的.

值得庆幸的.

查看bash函数:

sup() {
    ...
}
Run Code Online (Sandbox Code Playgroud)

把它放在你的~/.bashrc.


Var*_*han 24

运行shell时,有两种方法可以调用shell脚本:

  • 执行脚本会生成一个运行脚本的新进程.这是通过键入脚本名称来完成的,如果它是可执行的并以a开头

    #!/bin/bash
    行,或直接调用
    /bin/bash mycmd.sh

  • 获取脚本在其父shell(即您正在键入命令的那个)中运行它.这是通过键入来完成的

    source mycmd.sh
    要么
    . mycmd.sh

因此,未来源的shell脚本中的cd 永远不会传播到其父shell,因为这会违反进程隔离.

如果cd是您感兴趣的全部内容,您可以使用cd"快捷方式"删除脚本...在CDPATH env var中查看bash doc.

否则,您可以使用别名来键入单个命令,而不是源或.

alias mycmd="source mycmd.sh"
Run Code Online (Sandbox Code Playgroud)


Jon*_*ler 9

为它创建一个别名:

alias sup=". ~/bin/sup"
Run Code Online (Sandbox Code Playgroud)

或者沿着这些方向.

另请参阅:为什么cd不在bash shell脚本中工作?


通过反例回答评论:在Solaris 10上使用Korn Shell进行实验表明我能做到:

$ pwd
/work1/jleffler
$ echo "cd /work5/atria" > $HOME/bin/yyy
$ alias yyy=". ~/bin/yyy"
$ yyy
$ pwd
/work5/atria
$
Run Code Online (Sandbox Code Playgroud)

在Solaris 10上使用Bash(3.00.16)进行的实验也显示了相同的行为.



Tim*_*Tim 5

如果在调用时对脚本进行了子外壳处理,则无法在当前环境中获取脚本。

但是,您可以检查脚本的来源,如果没有,则强制脚本终止:

if [ -z "$PS1" ] ; then
    echo "This script must be sourced. Use \"source <script>\" instead."
    exit
fi
Run Code Online (Sandbox Code Playgroud)

以相同的方式,您可以强制脚本不是源脚本而是子外壳程序(保留当前的外壳程序环境):

if [ "$PS1" ] ; then
    echo "This script cannot be sourced. Use \"./<script>\" instead."
    return
fi
Run Code Online (Sandbox Code Playgroud)

两种版本均提供摘要:请参阅来源不提供