为位于我的一个文件夹中的 shell 脚本设置别名

Setting an alias for a shell script, located in one of my folders

所以我有这个文件夹 BashScripts 具有以下目录路径

/home/sadnan/BashScripts

/home/sadnan 是我的 $HOME。这是我打算放置自定义 shell 脚本的地方。目前只有一个名字叫cbi.sh。当我从文件夹内部 运行 时,该脚本按预期工作。现在我希望能够在全球范围内 运行 它。所以我将以下内容添加到我的 .bashrc 文件

#For my personal Bash Scripts
if [ -d $HOME/BashScripts ]; then
 PATH="$PATH:$HOME/BashScripts"
fi

alias cbi='. ./cbi.sh'

所以现在当我执行 echo $PATH 时,它会打印出以下内容

/home/sadnan/.nvm/versions/node/v12.18.0/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/home/sadnan/BashScripts

所以该文件夹似乎已添加到 PATH 中。如果我理解正确的话应该允许我在全球范围内 运行 我的 shell 脚本。

然后我还为脚本设置了一个别名并将其命名为cbi

但是现在当我在我的终端上 运行 cbi./cbi.sh 时,这就是我得到的

bash: ./cbi.sh: No such file or directory

我哪里做错了,我没做过多少 shell 脚本编写。但我认为这是要走的路。

我也试过alias cbi=`source ./cbi.sh'alias cbi=`sh ./cbi.sh' 两者都不起作用。

你必须 运行 cbi.sh:

# Wrong, the file is not named 'cbi'
cbi

# Wrong, the file is not in the current directory
./cbi.sh

# Wrong, same reason as above
alias cbi='. ./cbi.sh'
cbi

# Correct, this is the name of the file:
cbi.sh

./cbi.sh 表示 "run cbi.sh from the current directory"。因此,如果您不在 /home/sadnan/BashScripts 中,它将不起作用,因为它无法在当前目录中找到 cbi.sh

要确认您的 PATH 设置正确,请执行 which cbi.sh。应该 return /home/sadnan/BashScripts/cbi.sh.

如果您必须有一个别名,您可以alias cbi='/home/sadnan/BashScripts/cbi.sh'。这是确保正确执行的最简单方法。

要使上述所有工作正常,cbi.sh 必须是可执行的 (chmod u+x cbi.sh)。


如果您想获取它 (. cbi.sh) 而不是像可执行文件那样调用它,请像这样定义您的别名:

alias cbi='. /home/sadnan/BashScripts/cbi.sh'

研究执行和 "sourcing" 脚本之间的区别。



编辑:我根据@Diego 的评论删除了这段文字。

your PATH variable will not be used at all. You should then remove the PATH addition, and