1

I am very new to Bash Scripting and can not find any help online for the more basic stuff. My task is to run a program that attempts to take a user input and get it to 1 by dividing even numbers by 2 and multiplying odd numbers by 3 and adding 1. I don't know any advanced commands and I'm sure there are easier ways to do this but I cant quite understand why my code is giving me the "Command Not found" error from gedit.

My code:

#!/bin/bash
#Takes in a number and computes it into hailstone series while
#displaying each number onto the screen
echo Enter number:
read n

while [$n -gt 1] 
do
 if [$n % 2 -eq 0]
  then 
   let n=n/2
   echo $n
 else
  let n=n*3+1
  echo $n the number is header
 fi
done

My variable keeps skipping the first if statement and returning my "is header" check statement and I don't want it to. If I input 8 it should be modded by 2 -eq 0, therefore it should divide until it equals 1 or less.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Rep
  • 27
  • 4
  • You're not being careful enough with the spacing. You must use `[ $n -gt 1 ]` because the command name is `[` and the last argument to `[` must be `]`. Or you can use `[[` which is laxer about the spacing. Shell scripting requires a lot of care about spaces. – Jonathan Leffler Nov 11 '16 at 22:05
  • http://shellcheck.net/ is your friend, for finding syntax bugs without needing to get humans involved. – Charles Duffy Nov 11 '16 at 22:08
  • 1
    btw, in terms of how to think about it: `[` is a **command**, not language syntax. Just as you need to use two words to run `ls mydir` instead of `lsmydir`, you need to run `[ foo` instead of `[foo` to prevent the shell from looking for a different command named `[foo`. If you want things to be less confusing, use the command `test "$n" -gt 1` instead of `[ "$n" -gt 1 ]`, as `test` looks less like something that would be syntax elsewhere. – Charles Duffy Nov 11 '16 at 22:09
  • @JonathanLeffler, spaces are still required after `[[` and before `]]`. – Charles Duffy Nov 11 '16 at 22:12

1 Answers1

1

You need to put space after [ and before ]. So instead of while [$n -gt 1], write while [ $n -gt 1 ].

The same goes for [$n % 2 -eq 0], but that won't be much help because there's no % operator in [ ... ]. You can use ((...)) instead. I also rewrote the let commands with the simpler and more intuitive ((...)) syntax.

#!/bin/bash
echo Enter number:
read -r n

while ((n > 1))
do
    if ((n % 2 == 0))
    then 
        ((n /= 2))
        echo $n
    else
        ((n = n * 3 + 1))
        echo $n the number is header
    fi
done
janos
  • 120,954
  • 29
  • 226
  • 236