如何从任何位置执行 bash 脚本? [英] How to execute bash script from any location?

查看:36
本文介绍了如何从任何位置执行 bash 脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 UNIX 中,我读到将 shell 脚本移动到/usr/local/bin 将允许您通过简单地键入[scriptname].sh"并按 Enter 键从任何位置执行脚本.

In UNIX, I read that moving a shell script to /usr/local/bin will allow you to execute the script from any location by simply typing "[scriptname].sh" and pressing enter.

我移动了一个具有普通用户和 root 权限的脚本,但我无法运行它.

I have moved a script with both normal user and root permissions but I can't run it.

脚本:

#! bin/bash

echo "The current date and time is:"
date

echo "The total system uptime is"
uptime

echo "The users currently logged in are:"
who

echo "The current user is:"
who -m

exit 0

当我尝试移动然后运行脚本时会发生这种情况:

This is what happens when I try to move and then run the script:

[myusername@VDDK13C-6DDE885 ~]$ sudo mv sysinfo.sh /usr/local/bin

[myusername@VDDK13C-6DDE885 ~]$ sysinfo.sh

bash: sysinfo.sh: command not found

推荐答案

如果您想从任何地方运行脚本,您需要将它添加到您的PATH.通常 /usr/local/bin 位于每个用户的路径中,因此它应该以这种方式工作.所以检查你的系统 /usr/local/bin 是否在你的 PATH 中,在你的终端上:

If you want to run the script from everywhere you need to add it to your PATH. Usually /usr/local/bin is in the path of every user so this way it should work. So check if in your system /usr/local/bin is in your PATH doing, on your terminal:

echo $PATH 

您应该会看到列出了很多路径(例如 /bin/sbin 等...).如果未列出,您可以添加它.更好的解决方案是将所有脚本保存在一个目录中,例如在您的 home 中并将其添加到您的路径中.

You should see a lot of paths listed (like /bin, /sbin etc...). If its not listed you can add it. A even better solution is to keep all your scripts inside a directory, for example in your home and add it to your path.

要在路径中添加目录,您可以修改 shell init 脚本并添加新目录,例如,如果您使用 BASH shell,则可以编辑您的 .bashrc 并添加以下行:

To add a directory in your path you can modify your shell init scripts and add the new directories, for example if you're usin the BASH shell you can edi your .bashrc and add the line:

PATH=$PATH:/the_directory_you_want_to_add/:/another_directory/

这会将新目录附加到您现有的PATH.

This will append the new directories to your existing PATH.

这篇关于如何从任何位置执行 bash 脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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