Issues while trying to run a shell script using the command sh <filename.prog>

Hi,

I'm facing issues while trying to run a sample program on Linux.
If I try to run the script using the command "sh <filename.prog>", it doesn't work. But, if I try to execute it using the command "ksh <filename.prog>", it works fine.

Even ". ./filename.prog" works fine.

Can you please help in fixing this and make the file execute using the command "sh <filename.prog>".

Code:

#!/bin/sh
  
 printf "%s\n" "set pages 0 serverout on feed off" \
          "SELECT sysdate from dual;" \
           |sqlplus -s username/password \
           |{ read var1; }
echo "date is " $var1

Use code tags for code please, the button.

This particular script will only work in ksh because of the way its constructed. It puts read after a pipe, which is something you can do in ksh but not a vanilla bourne shell because of the opposite order they create subshells.

You could use $( ) braces instead of read here, which ought to work in both:

DATE=$(printf "%s\n" "set pages 0 serverout on feed off" \
          "SELECT sysdate from dual;" \
           |sqlplus -s username/password )
echo "date is $DATE"
1 Like

Thanks for your response Corona. We have a similar code in almost 70+ programs and it would be a little tough to change it every where. Would it be a good idea to make the "sh" present under "/bin" to point to "ksh" i.e. creating a soft link for sh to point to ksh and try running it?

I'd be wary of doing that. The difference you've just shown can as easily break programs as fix them, changing it globally could have wider problems, and #!/bin/sh is used by all sorts of system things.

Might it be easier to change the #!/bin/sh part to #!/bin/ksh in those 70+ programs?

I tried changing the first line from #!/bin/sh to #!/bin/ksh, but it didn't work.
It still doesn't work when I try to execute the script as "sh <filename.prog>"

That's because by running 'sh programname' you're asking sh to run that file. The #!/bin/ksh line only gets used when you do ./file.sh.

If they have to work in plain sh, you'll have to update them, they were definitely written for ksh.

2 Likes

Thank you Corona.

1 Like