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

0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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
@Delfin: I don't see them in your script above? How are you printing those colors?
I didn't place it for the minimum working example. But I am doing it this way: echo "\e[31m Example \e[0m"
@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'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.