Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux: Run a binary in a script

Tags:

linux

shell

sh

cd

i want to run a program via script. normally i type ./program in the shell and the program starts.

my script looks like this:

#!/bin/sh
cd  /home/user/path_to_the_program/
sh program

it fails, i think the last line went wrong...

i know this is childish question but thx a lot!

like image 665
co-worker Avatar asked Oct 17 '10 15:10

co-worker


People also ask

Can Linux run binary file?

In Linux and Unix-like operating systems, . bin files contain machine code in it and can be executed on the system. All the data encoded in binary files cannot be readable by humans. These files can store anything except text.


2 Answers

If ./program works in the shell, why not use it in your script?

#!/bin/sh
cd /home/user/path_to_the_program/
./program

sh program launches sh to try and interpret program as a shell script. Most likely it's not a script but some other executable file, which is why it fails.

like image 186
Nick Avatar answered Sep 18 '22 17:09

Nick


When you type

./program

The shell tries to execute the program according to how it determines the file needs to be executed. If it is a binary, it will attempt to execute the entry subroutine. If the shell detects it is a script, e.g through the use of

#!/bin/sh

or

#!/bin/awk

or more generally

#!/path/to/interpreter

the shell will pass the file (and any supplied arguments) as arguments to the supplied interpreter, which will then execute the script. If the interpreter given in the path does not exist, the shell will error, and if no interpreter line is found, the shell will assume the supplied script is to executed by itself.

A command

sh program

is equivalent to

./program

when the first line of program contains

#!/bin/sh

assuming that /bin/sh is the sh in your path (it could be /system/bin/sh, for example). Passing a binary to sh will cause sh to treat it as a shell script, which it is not, and binary is not interpretable shell (which is plain text). That is why you cannot use

sh program

in this context. It will also fail due to program being ruby, awk, sed, or anything else that is not a shell script.

like image 36
user1207217 Avatar answered Sep 21 '22 17:09

user1207217