2
while [ "$c" = y -o "$c" = Y -o -z $c ]
do
  echo enter a number;
  read n;
    if [ $n -ge 0 -a $n -le 50 ];then
      echo "cube= `expr $n * $n * $n`";
    fi;
  echo y to continue  or any to exit;
  read c;
done
  • To ask a better question, you should describe (or better, show) what actually happens, and describe how that differs from what you want to happen. – glenn jackman Jan 11 at 21:02
6

You've got a few problems with your shell script. First, you should quote $c in the while (all of them — you missed the last one). Otherwise, when $c is empty (say, at the start of your program), the -z test gets passed nothing instead of the empty string, giving an error (something along the lines of "argument expected").

Second, you need to escape the * in your expr command. Otherwise it's trying to do a glob (match filenames), just like cat * would do. Easiest is to escape it to \*. The error from that will depend on exactly what the * happens to expand to (i.e., which files are in your current directory), but will probably be something confusing!

That should at least get your script to run.

PS: There are a bunch more ways this could be improved, you might want to check out ShellCheck for some (automated) suggestions.

1

In bash, you could write:

PS3="Continue? "
while true; do

    read -p "Enter a number: " n
    ((0 <= n && n <= 50)) && echo "cube = $((n * n * n))"

    select ans in yes no; do
        case $ans in
            yes) break ;;
            no) break 2 ;;
        esac
    done
done

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.