在 Git Bash 中运行.sh 脚本

我在 Windows 机器上使用 Git 2.7.2. Windows.1和 MinGW 64。

我有一个 C:/path/to/scripts/myScript.sh的剧本。

如何从 Git Bash 实例执行此脚本?

可以将它添加到 .bashrc文件中,然后执行整个 bashrc 文件。

但是我想将脚本添加到一个单独的文件中,并从那里执行它。

227330 次浏览

Let's say you have a script script.sh. To run it (using Git Bash), you do the following: [a] Add a "sh-bang" line on the first line (e.g. #!/bin/bash) and then [b]:

# Use ./ (or any valid dir spec):
./script.sh

Note: chmod +x does nothing to a script's executability on Git Bash. It won't hurt to run it, but it won't accomplish anything either.

#!/usr/bin/env sh

this is how git bash knows a file is executable. chmod a+x does nothing in gitbash. (Note: any "she-bang" will work, e.g. #!/bin/bash, etc.)

If you wish to execute a script file from the git bash prompt on Windows, just precede the script file with sh

sh my_awesome_script.sh

I had a similar problem, but I was getting an error message

cannot execute binary file

I discovered that the filename contained non-ASCII characters. When those were fixed, the script ran fine with ./script.sh.

I was having two .sh scripts to start and stop the digital ocean servers that I wanted to run from the Windows 10. What I did is:

  • downloaded "Git for Windows" (from https://git-scm.com/download/win).
  • installed Git
  • to execute the .sh script just double-clicked the script file it started the execution of the script.

Now to run the script each time I just double-click the script

If by any chance you've changed the default open for .sh files to a text editor like I had, you can just "bash .\yourscript.sh", provided you have git bash installed and in path.

If your running export command in your bash script the above-given solution may not export anything even if it will run the script. As an alternative for that, you can run your script using

. script.sh

Now if you try to echo your var it will be shown. Check my the result on my git bash

(coffeeapp) user (master *) capstone
$ . setup.sh
done
(coffeeapp) user (master *) capstone
$ echo $ALGORITHMS
[RS256]
(coffeeapp) user (master *) capstone
$

Check more detail in this question

Once you're in the directory, just run it as ./myScript.sh

if you are on Linux or ubuntu write ./file_name.sh and you are on windows just write sh before file name like that sh file_name.sh

  1. For Linux -> ./filename.sh
  2. For Windows -> sh file_name.sh

#!/bin/bash at the top of the file automatically makes the .sh file executable. I agree the chmod does not do anything but the above line solves the problem. you can either give the entire path in gitbash to execute it or add it in the PATH variable export PATH=$PATH:/path/to/the/script then you an run it from anywhere