简体   繁体   中英

Linux: Run a binary in a script

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!

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.

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, eg 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.

You don't need the sh and looks like you don't have the path to the program in your $PATH .

Try this:

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

This should be enough:

/home/user/path_to_the_program/program

If that does not work, check the following:

  • executable bit
  • shebang line of the program (if it is a script)

You don't need the "sh" here. Just put "program" on the last line by itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM