简体   繁体   English

如何在不使用“sh”或“bash”命令的情况下运行 shell 脚本?

[英]How do I run a shell script without using "sh" or "bash" commands?

I have a shell script which I want to run without using the "sh" or "bash" commands.我有一个 shell 脚本,我想在不使用“sh”或“bash”命令的情况下运行它。 For example:例如:

Instead of: sh script.sh而不是: sh script.sh

I want to use: script.sh我想使用: script.sh

How can I do this?我怎样才能做到这一点?

PS (i) I don't use shell script much and I tried reading about aliases, but I did not understand how to use them. PS(i)我不经常使用 shell 脚本,我尝试阅读别名,但我不明白如何使用它们。

(ii) I also read about linking the script with another file in the PATH variables. (ii) 我还阅读了有关将脚本与 PATH 变量中的另一个文件链接的内容。 I am using my university server and I don't have permissions to create a file in those locations.我正在使用我的大学服务器,但我无权在这些位置创建文件。

Add a "shebang" at the top of your file:在文件顶部添加“shebang”:

#!/bin/bash

And make your file executable ( chmod +x script.sh ).并使您的文件可执行( chmod +x script.sh )。

Finally, modify your path to add the directory where your script is located:最后,修改您的路径以添加您的脚本所在的目录:

export PATH=$PATH:/appropriate/directory

(typically, you want $HOME/bin for storing your own scripts) (通常,您需要$HOME/bin来存储您自己的脚本)

These are the prerequisites of directly using the script name:这些是直接使用脚本名称的先决条件:

  1. Add the shebang line ( #!/bin/bash ) at the very top.在最顶部添加 shebang 行 ( #!/bin/bash )。
  2. Use chmod u+x scriptname to make the script executable (where scriptname is the name of your script).使用chmod u+x scriptname使脚本可执行(其中scriptname是脚本的名称)。
  3. Place the script under /usr/local/bin folder.将脚本放在/usr/local/bin文件夹下。
    • Note: I suggest placing it under /usr/local/bin because most likely that path will be already added to your PATH variable.注意:我建议将它放在/usr/local/bin因为该路径很可能已经添加到您的PATH变量中。
  4. Run the script using just its name, scriptname .仅使用脚本名称scriptname运行脚本。

If you don't have access to /usr/local/bin then do the following:如果您无权访问/usr/local/bin请执行以下操作:

  1. Create a folder in your home directory and call it bin .在您的主目录中创建一个文件夹并将其命名为bin

  2. Do ls -lA on your home directory, to identify the start-up script your shell is using.在您的主目录上执行ls -lA ,以识别您的 shell 正在使用的启动脚本。 It should be either .profile or .bashrc .它应该是.profile.bashrc

  3. Once you have identified the start up script, add the following line:确定启动脚本后,添加以下行:

     PATH="$PATH:$HOME/bin"
  4. Once added, source your start-up script or log out and log back in.添加后,获取启动脚本或注销并重新登录。

    To source, put .来源,把. followed by a space and then your start-up script name, eg . .profile后跟一个空格,然后是您的启动脚本名称,例如. .profile . .profile or . .bashrc . .profile. .bashrc . .bashrc

  5. Run the script using just its name, scriptname .仅使用脚本名称scriptname运行脚本。

Just make sure it is executable, using chmod +x .只需确保它是可执行的,使用chmod +x By default, the current directory is not on your PATH, so you will need to execute it as ./script.sh - or otherwise reference it by a qualified path.默认情况下,当前目录不在您的 PATH 中,因此您需要将其作为./script.sh执行 - 或者通过限定路径引用它。 Alternatively, if you truly need just script.sh , you would need to add it to your PATH.或者,如果您真的只script.sh ,则需要将其添加到您的 PATH 中。 (You may not have access to modify the system path, but you can almost certainly modify the PATH of your own current environment.) This also assumes that your script starts with something like #!/bin/sh . (您可能无权修改系统路径,但几乎可以肯定的是,您可以修改自己当前环境的 PATH。)这还假设您的脚本以#!/bin/sh类的内容开头。

You could also still use an alias, which is not really related to shell scripting but just the shell, and is simple as:您还可以使用别名,它与 shell 脚本并没有真正相关,而只是与 shell 相关,并且很简单:

alias script.sh='sh script.sh'

Which would allow you to use just simply script.sh (literally - this won't work for any other *.sh file) instead of sh script.sh .这将允许您仅使用script.sh (字面意思 - 这不适用于任何其他*.sh文件)而不是sh script.sh

In this example the file will be called myShell在本例中,该文件将被称为myShell

First of all we will need to make this file we can just start off by typing the following:首先,我们需要制作这个文件,我们可以通过键入以下内容开始:

sudo nano myShell

Notice we didn't put the .sh extension?注意我们没有放置.sh扩展名? That's because when we run it from the terminal we will only need to type myShell in order to run our command!那是因为当我们从终端运行它时,我们只需要输入myShell即可运行我们的命令!

Now, in nano the top line MUST be #!/bin/bash then you may leave a new line before continuing.现在,在 nano 中,顶行必须是#!/bin/bash然后你可以在继续之前留下一个新行。

For demonstration I will add a basic Hello World!为了演示,我将添加一个基本的Hello World! response回复

So, I type the following:所以,我输入以下内容:

echo Hello World!

After that my example should look like this:之后,我的示例应如下所示:

#!/bin/bash
echo Hello World!

Now save the file and then run this command:现在保存文件,然后运行以下命令:

chmod +x myShell

Now we have made the file executable we can move it to /usr/bin/ by using the following command:现在我们已经使文件可执行,我们可以使用以下命令将其移动到/usr/bin/

sudo cp myShell /usr/bin/

Congrats!恭喜! Our command is now done!我们的命令现在完成了! In the terminal we can type myShell and it should say Hello World!在终端中,我们可以输入myShell ,它应该会说Hello World!

You have to enable the executable bit for the program.您必须为程序启用可执行位。

chmod +x script.sh

Then you can use ./script.sh然后你可以使用./script.sh

You can add the folder to the PATH in your .bashrc file (located in your home directory).您可以将该文件夹添加到.bashrc文件(位于您的主目录中)的 PATH 中。 Add this line to the end of the file:将此行添加到文件末尾:

export PATH=$PATH:/your/folder/here

You can type sudo install (name of script) /usr/local/bin/(what you want to type to execute said script)您可以输入 sudo install (脚本名称)/usr/local/bin/(您要输入的内容来执行所述脚本)

ex: sudo install quickcommit.sh /usr/local/bin/quickcommit enter password例如: sudo install quickcommit.sh /usr/local/bin/quickcommit输入密码

now can run without .sh and in any directory现在可以在没有 .sh 的情况下在任何目录中运行

Add .添加 。 (current directory) to your PATH variable. (当前目录)到您的 PATH 变量。
You can do this by editing your .profile file.您可以通过编辑 .profile 文件来完成此操作。
put following line in your .profile file将以下行放在您的 .profile 文件中
PATH=$PATH:.

Just make sure to add Shebang ( #!/bin/bash ) line at the starting of your script and make the script executable(using chmod +x <File Name> ).只需确保在脚本开头添加 Shebang ( #!/bin/bash ) 行并使脚本可执行(使用chmod +x <File Name> )。

Here is my backup script that will give you the idea and the automation:这是我的备份脚本,它将为您提供想法和自动化:

Server: Ubuntu 16.04 PHP: 7.0 Apache2, Mysql etc...服务器:Ubuntu 16.04 PHP:7.0 Apache2、Mysql 等...

# Make Shell Backup Script - Bash Backup Script
    nano /home/user/bash/backupscript.sh
        #!/bin/bash
        # Backup All Start
        mkdir /home/user/backup/$(date +"%Y-%m-%d")
        sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/etc_rest.zip /etc -x "*apache2*" -x "*php*" -x "*mysql*"
        sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/etc_apache2.zip /etc/apache2
        sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/etc_php.zip /etc/php
        sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/etc_mysql.zip /etc/mysql
        sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/var_www_rest.zip /var/www -x "*html*"
        sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/var_www_html.zip /var/www/html
        sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/home_user.zip /home/user -x "*backup*"
        # Backup All End
        echo "Backup Completed Successfully!"
        echo "Location: /home/user/backup/$(date +"%Y-%m-%d")"

    chmod +x /home/user/bash/backupscript.sh
    sudo ln -s /home/user/bash/backupscript.sh /usr/bin/backupscript

change /home/user to your user directory and type: backupscript anywhere on terminal to run the script!将 /home/user 更改为您的用户目录并在终端上的任意位置键入: backupscript以运行脚本! (assuming that /usr/bin is in your path) (假设 /usr/bin 在您的路径中)

Enter "#!/bin/sh" before script.在脚本前输入"#!/bin/sh" Then save it as script.sh for example.然后将其保存为script.sh例如。 copy it to $HOME/bin or $HOME/usr/bin将其复制到$HOME/bin$HOME/usr/bin
The directory can be different on different linux distros but they end with 'bin' and are in home directory cd $HOME/bin or $HOME/usr/bin该目录在不同的 linux 发行版上可能不同,但它们以'bin'结尾并且位于主目录cd $HOME/bin$HOME/usr/bin
Type chmod 700 script.sh输入chmod 700 script.sh
And you can run it just by typing run.sh on terminal.您只需在终端上键入run.sh即可运行它。 If it not work, try chmod +x run.sh instead of chmod 700 run.sh如果它不起作用,请尝试chmod +x run.sh而不是chmod 700 run.sh

Make any file as executable将任何文件设为可执行文件


Let's say you have an executable file called migrate_linux_amd64 and you want to run this file as a command like "migrate"假设您有一个名为 migrate_linux_amd64 的可执行文件,并且您想将此文件作为“migrate”之类的命令运行

  1. First test the executable file from the file location:首先从文件位置测试可执行文件:
[oracle@localhost]$ ./migrate.linux-amd64 
Usage: migrate OPTIONS COMMAND [arg...]
       migrate [ -version | -help ]

Options:
  -source          Location of the migrations (driver://url)
  -path            Shorthand for -source=file://path 
  -database        Run migrations against this database (driver://url)
  -prefetch N      Number of migrations to load in advance before executing (default 10)
  -lock-timeout N  Allow N seconds to acquire database lock (default 15)
  -verbose         Print verbose logging
  -version         Print version
  -help            Print usage

Commands:
  goto V       Migrate to version V
  up [N]       Apply all or N up migrations
  down [N]     Apply all or N down migrations
  drop         Drop everyting inside database
  force V      Set version V but don't run migration (ignores dirty state)
  version      Print current migration version
  1. Make sure you have execute privileges on the file确保您对该文件具有执行权限
    -rwxr-xr-x 1 oracle oinstall 7473971 May 18 2017 migrate.linux-amd64
    if not, run chmod +x migrate.linux-amd64如果没有,运行chmod +x migrate.linux-amd64

  2. Then copy your file to /usr/local/bin .然后将您的文件复制到/usr/local/bin This directory is owned by root, use sudo or switch to root and perform the following operation该目录归root所有,使用sudo或切换到root执行以下操作

sudo cp migrate.linux-amd64 /usr/local/bin
sudo chown oracle:oracle /user/local/bin/migrate.linux.amd64
  1. Then create a symbolic link like below然后创建一个如下所示的符号链接
sudo ln /usr/local/bin/migrate.linux.amd64 /usr/local/bin/migrate
sudo chown oracle:oracle /usr/local/bin/migrate
  1. Finally add /usr/local/bin to your path or user profile最后将 /usr/local/bin 添加到您的路径或用户配置文件中
export PATH = $PATH:/usr/local/bin
  1. Then run the command as "migrate"然后将命令作为“迁移”运行
[oracle@localhost]$ migrate
Usage: migrate OPTIONS COMMAND [arg...]
       migrate [ -version | -help ]

Options:
  -source          Location of the migrations (driver://url)
  -path            Shorthand for -source=file://path 
  -database        Run migrations against this database (driver://url)
  -prefetch N      Number of migrations to load in advance before executing (default 10)
  -lock-timeout N  Allow N seconds to acquire database lock (default 15)
  -verbose         Print verbose logging
  -version         Print version
  -help            Print usage

Commands:
  goto V       Migrate to version V
  up [N]       Apply all or N up migrations
  down [N]     Apply all or N down migrations
  drop         Drop everyting inside database
  force V      Set version V but don't run migration (ignores dirty state)
  version      Print current migration version
  1. Make the script file as executable by using file's properties使用文件的属性将脚本文件设为可执行文件
  2. Create alias for the executable in ~/.bashrc.在 ~/.bashrc 中为可执行文件创建别名。 alias <alias namme> = <full script file path>'
  3. refresh the user session to apply it.刷新用户会话以应用它。 source ~/.bashrc

Just to add to what everyone suggested.只是为了补充每个人的建议。 Even with those solutions, the problem will persist if the user wants to execute the script as sudo即使使用这些解决方案,如果用户想以 sudo 执行脚本,问题仍然存在

example: chmod a+x /tmp/myscript.sh sudo ln -s /tmp/myscript.sh /usr/local/bin/myscript示例:chmod a+x /tmp/myscript.sh sudo ln -s /tmp/myscript.sh /usr/local/bin/myscript

typing myscript would work but typing sudo myscript would return command not found.输入 myscript 可以,但输入 sudo myscript 会返回 command not found。

As sudo you would have to still type sudo sh myscript or sudo bash myscript.作为 sudo,您仍然必须输入 sudo sh myscript 或 sudo bash myscript。

I can't think of a solution around this.我想不出解决这个问题的办法。

只是:

/path/to/file/my_script.sh

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

相关问题 PHP / Bash:如何运行Shell脚本,并在脚本具有“读取”命令的地方传递PHP变量? - PHP / Bash : How do I run a shell script, passing a PHP variable where the script has “read” commands? 如何从bash脚本运行django shell命令 - How can I run django shell commands from a bash script 如何在我的bash脚本中运行ruby命令而不出现“红宝石:找不到命令” - How do I run ruby commands in my bash script without getting “ruby: command not found” 如何在 bash 脚本中运行所有命令? - How do I run all the commands in a bash script? autoconf使用sh,我需要SHELL = BASH,我如何强制autoconf使用bash? - autoconf using sh, I need SHELL=BASH, how do I force autoconf to use bash? 使用shell脚本(bash)在单独的终端中运行命令 - Run commands in seperate terminal using shell script (bash) 如何使用Shell脚本运行2条命令 - how to run 2 commands using a shell script 从php执行Shell脚本,但是sh脚本中的命令无法运行 - Shell script executed from php, but commands in sh script wont run 我如何使用bash / sh shell从容器内部杀死容器进程(PID 1) - How do I kill the container process (PID 1) from inside the container using bash/sh shell 如何按计划在 Google Cloud Shell 上运行 .sh 脚本? - How can I run a .sh script on Google Cloud Shell on schedule?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM