简体   繁体   English

如何将bash脚本作为命令运行?

[英]How do you run bash script as a command?

I have a bash script, which I use for configuration of different parameters in text files in my wireless access media server. 我有一个bash脚本,用于在无线访问媒体服务器中的文本文件中配置不同的参数。

The script is located in one directory, and because I do all of configurations using putty, I have to either use the full path of the file or move to the directory that contains the file. 该脚本位于一个目录中,并且由于我使用腻子进行了所有配置,因此必须使用文件的完整路径或移至包含该文件的目录。 I would like to avoid this. 我想避免这种情况。

Is it possible to save the bash script in or edit the bash script so that I can run it as command, for example as cp or ls commands? 是否可以保存bash脚本或编辑bash脚本,以便我可以将其作为命令运行,例如作为cpls命令运行?

The script needs to be executable, with: 该脚本必须是可执行的,并具有:

chmod +x scriptname

(or similar). (或类似)。

Also, you want the script to be located in a directory that is in your PATH. 另外,您希望脚本位于PATH中的目录中。 To see your PATH use: 要查看您的PATH,请使用:

echo $PATH

Your choices are: to move (or link) the file into one of those directories, or to add the directory it is in to your PATH. 您的选择是:将文件移动(或链接)到这些目录之一中,或将文件所在的目录添加到PATH中。

You can add a directory to your PATH with: 您可以使用以下方式将目录添加到PATH:

PATH=$PATH:/name/of/my/directory

and if you do this in the file $HOME/.bashrc it will happen for each of your shell's automatically. 如果在$HOME/.bashrc文件中执行此操作,它将对每个shell自动进行。

You can place a softlink to the script under /usr/local/bin (Should be in $PATH like John said) 您可以在/ usr / local / bin下放置指向脚本的软链接(应该像John所说的那样位于$ PATH中)

ln -s /path/to/script /usr/local/bin/scriptname

This should do the trick. 这应该可以解决问题。

You can write a minimal wrapper in your home directory: 您可以在主目录中编写最小包装器:

#!/bin/bash
exec /yourpath/yourfile.extension

And run your child script with this command ./NameOfYourScript 然后使用此命令./NameOfYourScript运行子脚本

update : Unix hawks will probably say the first solution is a no-brainer because of the additional admin work it will load on you. 更新 :Unix鹰派可能会说第一个解决方案是理所当然的,因为它将为您加载额外的管理工作。 Agreed, but on your requirements, my solution works :) 同意,但是根据您的要求,我的解决方案有效:)

Otherwise, you can use an alias; 否则,您可以使用别名。 you will have to amend your .bashrc 您将不得不修改您的.bashrc

alias menu='bash /yourpath/menuScript.sh'

Another way is to run it with: 另一种方法是使用以下命令运行它:

/bin/bash /path/to/script

Then the file doesn't need to be executable. 然后,该文件不需要是可执行文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM