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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8779951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 21:27:31  来源:igfitidea点击:

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

bashshellaliassh

提问by Rameez Hussain

I have a shell script which I want to run without using the "sh" or "bash" commands. For example:

我有一个 shell 脚本,我想在不使用“sh”或“bash”命令的情况下运行它。例如:

Instead of: sh script.sh

代替: sh script.sh

I want to use: script.sh

我想使用: script.sh

How can I do this?

我怎样才能做到这一点?

P.S. (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. I am using my university server and I don't have permissions to create a file in those locations.

(ii) 我还阅读了有关将脚本与 PATH 变量中的另一个文件链接的内容。我正在使用我的大学服务器,但我无权在这些位置创建文件。

回答by fge

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/binfor storing your own scripts)

(通常,您想要$HOME/bin存储自己的脚本)

回答by jaypal singh

These are some of the prerequisites of directly using the script name:

这些是直接使用脚本名称的一些先决条件:

  1. Add the she-bang (#!/bin/bash)line at the very top.
  2. Using chmod u+x scriptnamemake the script executable. (where scriptnameis the name of your script)
  3. Place the script under /usr/local/binfolder.
  4. Run the script using just the name of the script.
  1. she-bang (#!/bin/bash)在最顶部添加一行。
  2. 使用chmod u+x scriptname使脚本可执行。(scriptname脚本的名称在哪里)
  3. 将脚本放在/usr/local/bin文件夹下。
  4. 仅使用脚本名称运行脚本。

Note:The reason I suggested to place it under /usr/local/binfolder is because most likely that will be path already added to your PATH variable.

注意:我建议将它放在/usr/local/bin文件夹下的原因是因为很可能该路径已经添加到您的PATH variable.

Update:

更新:

If you don't have access to the /usr/local/binfolder then do the following:

如果您无权访问该/usr/local/bin文件夹,请执行以下操作:

  1. Create a folder in your home directory and let's call it myscripts.
  2. Do ls -larton your home directory, to identify the start-up script your shell is using. It should either be .profileor .bashrc.
  3. Once you have identified the start up script, add the following line in your script - export set PATH=$PATH:~/myscript.
  4. Once added, source your start-up script or log out and log back in.
  5. Execute your script using scriptname.
  1. 在您的主目录中创建一个文件夹,我们称之为myscripts.
  2. 不要ls -lart在你的主目录,以确定您的外壳也使用启动脚本。它应该是.profile.bashrc
  3. 确定启动脚本后,在脚本中添加以下行 - export set PATH=$PATH:~/myscript.
  4. 添加后,获取启动脚本或注销并重新登录。
  5. 使用scriptname.

回答by ziesemer

Just make sure it is executable, using 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. Alternatively, if you truly need just script.sh, you would need to add it to your 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.

只需确保它是可执行的,使用chmod +x. 默认情况下,当前目录不在您的 PATH 中,因此您需要将其作为./script.sh- 或以其他方式通过限定路径引用它。或者,如果您真的只需要 ,则需要script.sh将其添加到 PATH 中。(您可能无权修改系统路径,但您几乎肯定可以修改您自己当前环境的 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 *.shfile) instead of sh script.sh.

这将允许您简单地使用script.sh(字面意思 - 这不适用于任何其他*.sh文件)而不是sh script.sh.

回答by ziesemer

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 .shextension? That's because when we run it from the terminal we will only need to type myShellin order to run our command!

请注意我们没有放置.sh扩展名?那是因为当我们从终端运行它时,我们只需要输入myShell即可运行我们的命令!

Now, in nano the top line MUST be #!/bin/bashthen you may leave a new line before continuing.

现在,在 nano 中,顶行必须是#!/bin/bash然后你可以在继续之前留下一个新行。

For demonstration I will add a basic Hello World!response

为了演示,我将添加一个基本Hello World!响应

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:

现在保存文件,然后运行以下命令:

sudo 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/

Just to make sure that the machine can execute it properly we will need to reboot the machine

只是为了确保机器可以正确执行它,我们需要重新启动机器

I used sudo shutdown -r now

我用了 sudo shutdown -r now

Congrats! Our command is now done! In the terminal we can type myShelland it should say Hello World!

恭喜!我们的命令现在完成了!在终端中我们可以输入myShell它应该说Hello World!

回答by Uku Loskit

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 .bashrcfile (located in your home directory). Add this line to the end of the file:

您可以将该文件夹添加到文件中的 PATH .bashrc(位于您的主目录中)。将此行添加到文件末尾:

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

回答by JoelWass

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/quickcommitenter password

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

now can run without .sh and in any directory

现在可以在没有 .sh 的情况下在任何目录中运行

回答by Arpit Tyagi

Add . (current directory) to your PATH variable.
You can do this by editing your .profile file.
put following line in your .profile file
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>).

添加 。(当前目录)到您的 PATH 变量。
您可以通过编辑 .profile 文件来完成此操作。
把下面这行放在你的 .profile 文件中
PATH=$PATH:.

只要确保#!/bin/bash在你的脚本开头添加 Shebang ( ) 行并使脚本可执行(使用chmod +x <File Name>)。

回答by Tarik

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: backupscriptanywhere on terminal to run the script! (assuming that /usr/bin is in your path)

将 /home/user 更改为您的用户目录并在终端上的任意位置键入:backupscript以运行脚本!(假设 /usr/bin 在您的路径中)

回答by Gyan Prakash

Enter "#!/bin/sh"before script. Then save it as script.shfor example. copy it to $HOME/binor $HOME/usr/bin
The directory can be different on different linux distros but they end with 'bin'and are in home directory cd $HOME/binor $HOME/usr/bin
Type chmod 700 script.sh
And you can run it just by typing run.shon terminal. If it not work, try chmod +x run.shinstead of chmod 700 run.sh

"#!/bin/sh"在脚本之前输入。然后将其保存script.sh为示例。将其复制到 $HOME/bin$HOME/usr/bin
目录在不同的 linux 发行版上可能不同,但它们以 'bin'和 位于主目录 cd $HOME/bin$HOME/usr/bin
Type 中 chmod 700 script.sh
并且您只需run.sh在终端上键入即可运行它 。如果它不起作用,请尝试 chmod +x run.sh代替 chmod 700 run.sh

回答by Guru

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:
  1. 首先从文件位置测试可执行文件:
[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

  2. Then copy your file to /usr/local/bin. This directory is owned by root, use sudo or switch to root and perform the following operation

  1. 确保您对该文件具有执行权限,
    -rwxr-xr-x 1 oracle oinstall 7473971 May 18 2017 migrate.linux-amd64
    如果没有,请运行chmod +x migrate.linux-amd64

  2. 然后将您的文件复制到/usr/local/bin. 该目录归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
  1. 然后创建一个如下所示的符号链接
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
  1. 最后将 /usr/local/bin 添加到您的路径或用户配置文件中
export PATH = $PATH:/usr/local/bin
  1. Then run the command as "migrate"
  1. 然后将命令作为“迁移”运行
[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