-1

I have a simple hello_world.c file from here. I figured it out how to do it.

gcc -Wall -g hello_world.c -o hello is working however if I run bash hello there's an error: hello: hello: cannot execute binary file

sh hello then error: hello: 1: Syntax error: "(" unexpected
./hello prints out the expected line.

I thought all three of these are the same. From the result it's not. Why the other two are not working? Except ./hello, is there any other way to invoke the file hello?

3

2 Answers 2

4

The first two attempts, bash hello and sh hello, you are trying to convince those shells (bash and sh respectively) that the hello file is a shell executable. Since it's a binary, the shells don't know how to handle being told to run it, so they give you those error messages. The third example, you are running the hello binary as a binary, the way a shell expects it to be run. The ./ is simply an indicator for where the binary can be found- in the current directory (.). Why do you need the ./? Most of the time, the "current working directory" isn't a part of the $PATH variable, so simply running hello wouldn't find the executable anywhere.

3

Why do we use ./ (dot slash) to run Linux scripts?

The Unix ./ script syntax can be explained in three parts:

The role of the application PATH in Linux The ./ notation denotes the current directory The need to avoid conflicts with existing commands

Unix’s dot slash vs the PATH Every computer has an application PATH. This is a collection of directories in which the OS looks when an executable command or runnable script is invoked.

All of the built-in commands you are familiar with, such as ls, cat, echo, touch, and chmod, are on the application PATH. Users often put the commonly used programs in the JDK or Git on the application PATH as well.

The problem is, if you’re trying to invoke a script you wrote yourself, it’s likely not saved in a folder that’s part of the application PATH. This means if you run your custom script like you would a command that resides on the PATH, the Linux OS won’t find it.

Meaning of ./ in Linux This is where the dot slash ./ notation comes in. It means “Look in the current directory.” When you use ./, you tell Ubuntu or Fedora or SUSE or whatever Linux distribution you’re using to look in the current directory for the command you wish to run, and completely ignore what’s on the application PAT

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .