3

So I just started learning UNIX and need a very basic question answered! I have spent hours searching for the correct way, but it seems I cant really get my head around it!

I have script called "contactdetails". I would like to run it by just typing in "contactdetails" in any directory, but the only way I can run it is by typing in "sh contactdetails".

Now I've heard I should add "#!/bin/sh" to the top line of my script, yet that has not worked. I have also been told I need to add it the $PATH environmental variable. I don't really understand what that means, and I when I type "echo $PATH" I get "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games".

When I try to create a directory/file in the "/usr" directory, I get the message "Permission Denied". I logging onto UNIX via my works server, so is that the problem? Is there a way for me to run the script by just typing its name as opposed to sh itsname?

Thanks in advance!

edit: I have also changed permissions to executable (chmod 755 contactdetails) if thats of any relevance! And i'm using PuTTY!

4

4 回答 4

5

你必须使它可执行

chmod +x contactdetails

并在您的路径中拥有它所在的目录,例如,如果您的脚本在/dir/with/script

   export PATH=$PATH:/dir/with/script

如果您将此行添加到您的.bashrc,它将PATH为每个 bash shell设置

或将其放入/usr/local/sbin, /usr/local/bin, /usr/sbin, /usr/bin,/sbin:/bin/usr/games(您需要以root用户身份执行此操作)

于 2013-06-16T10:19:24.030 回答
0

必须将该脚本(当然,其中包含 shebang)复制到$PATH. 像这样:

cp myscript /usr/bin/

如果您没有对这些目录的写入权限,那么就是这样。或者您也可以将您的文件夹设置$PATH为包含您自己的文件夹:

set PATH="$PATH:/path/to/mydir"
于 2013-06-16T10:20:07.963 回答
0

/usr 归根用户所有,因此您无权访问。您需要有凭据才能写入该目录。

$PATH 包含您的操作系统在您发出没有完整路径的命令时检查的目录。您可以使用 $PATH = $PATH:Additional directory 将目录添加到路径。

首选的方法是按照 H2CO3 的建议,您应该始终按照 parkydr 的建议使您的脚本可执行。

于 2013-06-16T10:22:50.620 回答
0

虽然您可以将脚本放在任何地方,但我的做法是使用我的 $HOME/bin,当我将该信息添加到我的配置文件时,我会在扩展之前保存现有的 PATH。将这两行添加到您的 $HOME/.profile 中:

ORIG_PATH=${ORIG_PATH:-$PATH};   export ORIG_PATH
PATH=$ORIG_PATH:$HOME/bin

因此,您是否必须重新访问您的个人资料:

$ . $HOME/.profile

上面的第一行已经保存了您的 ORIG_PATH 并且对配置文件的连续重新访问不会无限期地增加您的 PATH。

于 2013-06-16T10:46:25.947 回答