How to make a file executable in linux?

Asked by Satyam

To give a little more context, I think that this question stems from the distinction between executable and non executable files on windows, characterized by the .exe extension.

In linux, every file can be an executable.

Let’s see what happens when you try to execute a file. First, we need to have a file. We can use the echo command and redirect its output to create a new file.

> echo '#!/bin/bash' > hello
> echo 'echo hi' >> hello
> cat hello
#!/bin/bash
echo hi

Note the lack of extension in the filename. We could have named it hello.txt, or hello.sh, it’s entirely upto us, the extension mostly doesn’t matter. Unlike windows, you don’t need a special extension to make a file executable.

Now, we’ll execute the file.

> chmod +x hello
> ./hello
hi

Let’s go over what happened.

To execute a file all we need to do is enter the path of the file on the command prompt. We’ll also need execute permissions on the file, like to read a file we’d need read permissions. Note that setting or removing the execute permissions does not make a file executable or non-executable, but it just takes away or gives us the ability to execute it.

What exactly happens when we ‘execute’ a file is that the contents of the file are sent to the program located on the first line. In this case, it’s /bin/bash. 
 This means that all contents of the file are being sent to bash. So it’s as if you were typing those commands into the shell. Therefore, in the file we’ve created it ran the echo command.

Please note that there’s nothing special with ./, it just simply means ‘look for the file in the current directory’. It could have been any path, for example

> mkdir subdir
> mv hello subdir
> ./subdir/hello
hi

And you could also have some other program handle the execution. For example, consider the following file in which I’ve set the first line to be the location of python binary, which I found via the command whereis python. It may be different on your system.

> cat hello
#!/usr/bin/python
print "hello from python!"
> ./hello
hello from python!

You could also set a .doc file’s permissions as executable, or a .jpg file. It’s perfectly legal. But when you try to execute those, their contents will be sent to shell to be parsed as shell commands. But they aren’t shell commands, so you’ll get an error.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.