codenko
codenko

Reputation: 65

Issues with c shell escape character for *

So first and foremost, this is homework. Just struggling with something that I can't find out too much information about through google.

Question is print the product of the integers from 1 through the number entered.

So if we input 4, we give 24 (1*2*3*4) as the output.

My question is, I can't figure out how to escape the * character to concatenate it to my string. I have this working on bourne shell, but keep running into this issue in c shell.

@ temp = 1
@ ans = 1
while ( $temp <= $number )
    @ ans = ( $ans * $temp )
    @ temp = ( $temp + 1 )
end
set ans = "$ans ("
@ count = 1
while ( $count <= $number )
    set ans = "$ans$count"
    @ count = ( $count + 1 )
    if ( $count <= $number ) then
        set ans = "$ans*"
    endif
end
set ans = "$ans)"
echo $ans   

Any help or pointers would be much appreciated. Thanks!

Upvotes: 2

Views: 1055

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 753695

When echoing variables, use double quotes around the variable (echo "$ans") to avoid having the shell expand metacharacters in the variable's value:

(Script file: prod.csh):

#!/bin/tcsh

@ number = 6
@ temp = 1
@ ans = 1
while ( $temp <= $number )
    @ ans = ( $ans * $temp )
    @ temp = ( $temp + 1 )
end
set ans = "$ans ("
@ count = 1
while ( $count <= $number )
    set ans = "$ans$count"
    @ count = ( $count + 1 )
    if ( $count <= $number ) then
        set ans = "$ans*"
    endif
end
set ans = "$ans)"
echo "$ans"

Example run:

$ tcsh prod.csh
720 (1*2*3*4*5*6)
$

Upvotes: 1

Riftus
Riftus

Reputation: 394

set star = "*"
set ans = "$ans$star"

Edit How do I escape the wildcard/asterisk character in bash? Quotes needed for your echo:

echo "$ans"

Upvotes: 1

Related Questions