2

Suppose I have a shell script file foo.sh.

I can do chmod + x foo.sh and change it into an executable file.

In Kernighan-Pike: Unix Programming Environment (UP) they show that after this typing foo should execute the script. Instead in my Ubuntu system I need to type sh foo or ./foo. I am guessing this is due to some feature of the shell that wasn't present earlier (when UP was written). I will appreciate if some can enlighten me why this difference exists and why is it important?

5
  1. The name of the executable is important. If your file is named foo.sh, then executing foo will not work unless there is some other executable named foo. Unlike Windows, Unix does not do implicit file extensions.

  2. If the following works:

    ./foo.sh
    

    But this doesn't:

    foo.sh
    

    That means that the file is in your current directory and your current directory is not in your PATH. For your protection, if you don't explicitly provide the path to a command, the shell will only look for the command among files that are in your PATH.

  3. Spaces are important. The following may work:

    ./foo.sh
    

    But, this (taken from the first version of this question) certainly will not work:

    ./ foo.sh
    

    With a space between ./ and foo.sh, the shell will think that you want to execute the current directory with foo.sh as an argument. This will generate an error message.

  • 1
    Note that back when Kernighan&Pike was written, it was common to have the current directory (".") in the PATH (meaning that foo.sh would work without the ./). This was a found to be a security problem (someone could leave e.g. a malicious script named "ls" in their directory, then trick other people into running it), so it's no longer common (or recommended) practice. – Gordon Davisson Apr 7 '15 at 1:27
  • 2
    @Gordon; the problem with the . in PATH was specifically considered bad if you have the . at the beginning of the PATH sequence. If you have the . at the end of PATH the system commands (like your ls sample) will always be found (and executed) before the executables in . (the current directory). – Janis Apr 7 '15 at 3:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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