1

Contents of emp1.sh script

#!/bin/bash
#emp1.sh: interactive version uses read to take input

echo "Enter the pattern to be searched: \c"
read pname
echo "Enter the file to be used: \c"
read flname
echo "searching for the pattern $pname from the file $flname"
grep "$pname" $flname
echo "Selected records are shown above"

Why there is a difference between the outputs?

$ sh emp1.sh
Enter the pattern to be searched: 
$ ./emp1.sh
Enter the pattern to be searched: \c
1
  • 1
    That script is wrong both as an sh-script and as a bash-script. As an sh script, printf should be used instead of echo. As a bash script, read's -p should be used instead of echo. E.g. read -ep "Enter file to be used: " flname
    – geirha
    Jan 8, 2014 at 22:18

2 Answers 2

5

There are two different shells in fact. One is /bin/bash and other is /bin/dash. And /bin/sh is actually a softlink of /bin/dash. To verify it, write in terminal,

which sh

you will get output: /bin/sh

Next type ls -l /bin/sh in terminal, which will return something like,

lrwxrwxrwx 1 root root 4 May 16 20:23 /bin/sh -> dash

Which shows the fact that sh is a softlink of /bin/dash. you can try further which dash.

Actually bash is sh with more features and better syntax. Both of them have almost same commands, but they are different.

What is happening here

When you are running sh emp1.sh then script is handled by dash but when you run ./emp1.sh due to the shebang line(#!/bin/bash) on top of the script bash shell handles it. So you get slight different formatting in output. Keep in mind bash has some improved syntax.

0
-1

The output is different because you are using two different programs.

In the first case sh emp1.sh you start a program named sh and tell it to execute the instructions in emp1.sh. That program sh is probably the bourne shell (sh), a bourne again shell (bash) trying to emulate the classic shell (and thus reacting differently from its native mode), dash or even anything else.

When you use ./emp1.sh you try to execute the script empt1.sh itself. Its first line contains a shebang and an interpreter (#!/bin/bash) telling it that it needs to use bash (and all its features).

That means you use a different program/mode than in the first case. And you get different output.

To verify this, try one of these two:

  • /bin/bash emp1.sh (which should produce the same output as the ./emp1.sh)
  • Or change the first line to #!/bin/sh.
1
  • /bin/sh is a POSIX shell in modern UNIX and UNIX-like systems. You luckily don't see bourne as /bin/sh much anymore. In the case of Ubuntu, dash is used as sh by default.
    – geirha
    Jan 8, 2014 at 22:04

You must log in to answer this question.

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