Question

I have to write a tcsh script for unix that pulls values from every other line in a text file, compares them and decides if you should buy(1), sell(-1) or do nothing(0). Basically a simple stock profit calculation. I think I have all the logic right, but when I run the script I get a "while syntax error" and it never executes. I have the full script below, is it not possible to nest statements in a while loop with unix? If so any suggestions how to do this?

#!/bin/tcsh

set lineNum='wc -l testcase.txt'
set i=1
while ($i<$lineNum) 
   set prices='sed -n '$lineNump' testcase.txt'
   set arr=( $price )
   set j='echo ${#arr}'
   set price=0
   set x=0
   set y=0
   set k=0
   while ($k < $j)
      set a=arr[$k]
      set str=""
      if ($a>$price)
      then
          str="$str 1"
          price=$((price-a))
      else if($a<$price)
      then
          str="$str -1"
          price=$((price+a))
      else if($a==$price)
      then
          str="$str 0"
      fi
      str="$str $price"
      if ($str=='sed -n'('expr $lineNum+1'p)' testcase.txt')
      then
          x=$((x+1))
      fi
      y=$((y+1))
    end
lineNum=$((lineNum+2))
end
echo $x/$y
Was it helpful?

Solution

Your script appears to be a mixture of tcsh and bash syntax.

As Mark's answer says, the then keyword has to be on the same line as the if (unless you use a backslash to splice two lines, but there's not much point in doing that).

For a variable assignment, the set keyword is not optional; this:

str="$str 1"

is a syntax error in csh/tcsh (it will probably look for a command whose name starts with "str=".) Write that as:

set str = "$str 1"

Note that you can optionally have spaces around the = in a set. tcsh's syntax is a bit messed up:

set foo=bar   # ok
set foo = bar # ok
set foo= bar  # ok
set foo =bar  # error: "Variable name must begin with a letter."

The x=$((x+1)) syntax is specific to bash and related shells. tcsh uses @ for arithmetic assignments:

set x = 42
@ x ++        # sets $x to 43
@ x = $x * 2  # sets $x to 86

If you have a choice, I suggest writing your script to use bash rather than tcsh (you're about halfway there already). Its syntax is much more regular.

The classic rant about csh/tcsh programming can be found here.

OTHER TIPS

You are missing the end statement correspoding to the first while.
You are also using fi instead of endif. The "then" keywords need to be on the same line as the "if" they belong to.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top