views:

17139

answers:

4

I know it, forgets it and relearn it again. Time to write it down.

+2  A: 

To start the shell-script 'file.sh':

sh file.sh

bash file.sh

Another option is set executable permission using chmod command:

chmod +x file.sh

Now run .sh file as follows:

./file.sh
P-A
+1  A: 

For the bourne shell:

sh myscript.sh

For bash:

bash myscript.sh
anon
Thank you for answering this quite obvious question. For a Mac guy like me it is easy to forget the old Unix commands between the laps.
P-A
+15  A: 

To run a non-executable sh script, use:

sh myscript

To run a non-executable bash script, use:

bash myscript

To start an executable (which is any file with executable permission); you just specify it by its path:

/foo/bar
/bin/bar
./bar

To make a script executable, give it the necessary permission:

chmod +x bar
./bar

When a file is executable, the kernel is responsible for figuring out how to execte it. For non-binaries, this is done by looking at the first line of the file. It should contain a hashbang:

#! /usr/bin/env bash

The hashbang tells the kernel what program to run (in this case the command /usr/bin/env is ran with the argument bash). Then, the script is passed to the program (as second argument) along with all the arguments you gave the script as subsequent arguments.

That means every script that is executable should have a hashbang. If it doesn't, you're not telling the kernel what it is, and therefore the kernel doesn't know what program to use to interprete it. It could be bash, perl, python, sh, or something else. (In reality, the kernel will often use the user's default shell to interprete the file, which is very dangerous because it might not be the right interpreter at all or it might be able to parse some of it but with subtle behavioural differences such as is the case between sh and bash).

lhunath
Thank you for taking the time to write a good answer to a simple question.
P-A
A: 

If you want the script to run in the current shell (e.g. you want it to be able to affect your directory or environment) you should say:

. /path/to/script.sh

or

source /path/to/script.sh

Note that /path/to/script.sh can be relative, for instance . bin/script.sh runs the script.sh in the bin directory under the current directory.

Chas. Owens
Be **very** careful when sourcing or dot'ing with relateive pathnames. You should **always** start them with ./ If you don't do this, and the relative pathname doesn't contain any slashes, you'll be sourcing something in PATH, BEFORE something in the current directory! Very dangerous for abuse.
lhunath