Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I am under the impression that if I include the line

#!/bin/bash

at the start of my file, it will be recognized as a bash script that I can run just by

file.sh

instead of

sh file.sh

But in my case, file.sh gives something like test.sh gives test.sh: command not found. Why is that?

UPDATE

I notice I need to use ./. But I thought it will look in the current directory anyway?

./test.sh
share|improve this question
2  
Did you include \#!/bin/bash in your file as you write? There shouldn't be a backslash in the beginning. –  N.N. Aug 13 '11 at 13:15
    
Nono thats a typo ... also see update –  Jiew Meng Aug 13 '11 at 13:49
1  
No, it doesn't work in the current directory unless, the current directory is in your PATH. You can edit your PATH to always include the current directory ., but it is not recommended. –  frabjous Aug 13 '11 at 13:54
3  
sh file.sh and ./file.sh are not equal if the first line is #!/bin/bash! The correct way to execute bash scripts is by using bash file.sh. Also, using the .sh extension is discouraged because of the confusion ("it says .sh, so I must use sh file.sh right?") –  Lekensteyn Aug 13 '11 at 13:59

2 Answers 2

up vote 12 down vote accepted

First you need to make sure the file is executable:

chmod +x file.sh

And then to run it, you either need to put it in your PATH, i.e., one of the directories of files the OS searches when looking for files to run, which you can find with echo $PATH, or else you need to type in:

./file.sh

Rather than just type file.sh.

You can just type file.sh, if it's in your PATH, which I recommend. A good place is in ~/bin. Create that folder if it's not there, and under Ubuntu, it'll get added to your path when you log in.

share|improve this answer

You need to start it with ./file.sh, because the current dir is not in the PATH.

If this isn't sufficient, becaused you missed, what frabjous suggests, to chmod a+x, you should start programs beginning with a shebang #!/bin/bash with

bash file.sh

not

sh file.sh

even if sh is a symbolic link to /bin/bash.

The shell checks how it was invoked, and can be invoked as sh to act in a compatible mode, therefore it can fail to handle some bashisms, which would work if invoked as bash file.sh.

That was not your problem, but might become one, if you don't know these subtle distinction.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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