2

This may be a duplicate of bash user input if, but the answers do not solved my problem, so I think there is something else.

I have the next script:

#!/bin/bash

echo "Do that? [Y,n]"
read input
if [[ $input == "Y" || $input == "y" ]]; then
        echo "do that"
else
        echo "don't do that"
fi

and when I do sh basic-if.sh

enter image description here

Also I have

#!/bin/bash

read -n1 -p "Do that? [y,n]" doit 
case $doit in  
  y|Y) echo yes ;; 
  n|N) echo no ;; 
  *) echo dont know ;; 
esac

and when I do sh basic-if2.sh

enter image description here

I think my bash has a problem because appereatly the other users didn't have these problems running those examples. Thanks

Inian
  • 80,270
  • 14
  • 142
  • 161
Dau
  • 419
  • 1
  • 5
  • 20

1 Answers1

2

Running the script with sh scriptname overrides any default interpreter set inside your script. In your case the bourne shell (sh) runs the script instead of the bourne again shell (bash). The sh does not support [[ and the read command in its POSIX compliant form does not support -n flag.

In all likelihood, your sh in your system is not symlinked to bash and it is operating in itself as a POSIX compliant shell. Fix the problem by running

bash basic-if2.sh

or run it with a ./ before the script name there by making the system to look out for the interpreter in the first line of the file (#!/bin/bash). Instead of fixing the interpreter you could also do #!/usr/bin/env bash for the OS to look up where bash is installed and execute with that.

chmod a+x basic-if2.sh
./basic-if2.sh

You could additionally see if ls -lrth /bin/sh to see if its symlinked to dash which is a minimal POSIX compliant shell available on Debian systems.

Inian
  • 80,270
  • 14
  • 142
  • 161
  • Oh, that fixed the problem, but now it created another, the change of color in the fonts `\e[31m Example \e[0m` are not recognized – Dau Mar 01 '19 at 07:28
  • @Delfin: I don't see them in your script above? How are you printing those colors? – Inian Mar 01 '19 at 07:34
  • I didn't place it for the minimum working example. But I am doing it this way: `echo "\e[31m Example \e[0m"` – Dau Mar 01 '19 at 07:35
  • 1
    @Delfin: It is because `echo` does not recognize ANSI color codes by default without doing `echo -e`. But the latter is not portable in POSIX systems. Recommend using `printf '\e[31m Example \e[0m\n'` – Inian Mar 01 '19 at 07:38