up vote 5 down vote favorite
share [g+] share [fb]

So I've written my first bash script:

#!/bin/bash
echo 'hello world!'
exit

I know it has the right location to bash and is executable:

$ which bash
/bin/bash
$ chmod +x myscript.sh

Now I want to run it from the command line, but I get an error:

$ myscript.sh
myscript.sh: command not found

So instead I try this and it works:

$ bash myscript.sh
hello world!

Is this how I will always need to execute it? I feel like I have executed other scripts without having to precede it with bash. How can I run myscript.sh without having to precede it with bash?

Update: Here is a good explanation of why and how to execute a bash script.

link|improve this question

65% accept rate
feedback

3 Answers

up vote 13 down vote accepted

You have to make the file executable. You can do that with

chmod +x <filename>

where is the name of your script and then you have to prepend it with ./ to instruct the shell to run a file in the local directory, like:

./script.sh

You can only run files that are in your PATH or that you specify a path to them. ./, the local directory, is not in the PATH by default because someone may use it for nefarious purposes. Imagine a script called ls dropped in a directory, you go inside that directory, run ls and that script does something bad.

While you are at it you may want to make it more portable by running shell instead of bash by using:

#!/bin/sh

or by running bash no matter where it is installed as long as it is installed:

#!/usr/bin/env bash
link|improve this answer
I have already done that with chmod +x myscript.sh. Did I do it wrong? – Andrew Dec 12 '09 at 19:28
You are probably missing ./ I've added it to the answer. – J. Pablo Fernández Dec 12 '09 at 19:30
Makes sense. And it works. Thanks! – Andrew Dec 12 '09 at 19:34
feedback

In addition to the advice by Fernández, precede it with a point, like this:

./myscript.sh

For security reasons the current directory is never included in the execution path.

link|improve this answer
feedback

Yes, your problem is a path issue. But I am interested in reading harrymc's security reasons for not including current directory in the execution path.

link|improve this answer
If your computer is compromised or if you innocently unpack a tgz file into the current directory and there's an executable called, for example, ls, then having the current directory in your PATH could cause the one in the current directory to be executed instead of the one in /usr/bin. – Doug Harris Jan 6 '10 at 20:31
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.