apil.tamang
apil.tamang

Reputation: 2725

bash, executable runs in commandline but not in script

Here's the deal. I've got cygwin installed in Win7 envionment. This is the sequence of things I would do in a command line and everything works,

File mpc.exe is a 64-bit executable created by Intel Fortran Compiler

cp ./dir1/dir2/mpc.exe ./mpc.exe
./mpc.exe arg1 arg2

everything is fine

Want to create a script for that. The reason is I will want to execute the code for various values of arg2. file "script_mpc.sh" contains following,

#!/bin/sh
cp ./dir1/dir2/mpc.exe ./mpc.exe
./mpc.exe arg1 arg2
wait
return_val=$?
[ $retval -eq 0 ] && echo "successfully executed "

Now back at the command line,

$>chmod +x script_mpc.sh
$>./script_mpc.sh

error:

./script_mpc.sh: line 2: ./mpc.exe: No such file or directory

A very fresh beginner. Learning shell commands and scripting on the go. Please help.

Upvotes: 1

Views: 1186

Answers (1)

Keith Thompson
Keith Thompson

Reputation: 263297

You're on Cygwin.

I'll bet that this line:

cp ./dir1/dir2/mpc.exe ./mpc.exe

has a Windows-style CR-LF line ending. The shell (either sh or bash) interprets the CR as part of the filename, so it copies the file to "./mpc.exe\r".

Filter the script through dos2unix. Be sure to read the man page first; unlike most text filters, it normally overwrites the input file.

Background:

Unix uses a single ASCII LF character to mark the end of a line in a text file. Windows uses a CR-LF pair. Cygwin is a Unix-like emulation layer on top of Windows, so it tends to be a rich source of problems with conflicting end-of-line representations.

Unix shells, in particular, typically don't recognize the CR as part of an end-of-line indicator; instead, they treat it as just another character -- one that tends to be invisible, depending on how you look at the file.

You probably have a mixture of LF and CR-LF line endings. If it used CR-LF endings consistently, then the #!/bin/sh or #!/bin/bash line wouldn't be recognized.

If possible, use only Unix-style editors (vim, emacs, nano, or whatever you prefer) to edit shell scripts. If you create a script using, say, Notepad or Wordpad, you're likely to run into this kind of problem.

Upvotes: 1

Related Questions