Mike
Mike

Reputation: 85

How to assign variables in a csh script and used them as arguments for that same script?

Good day,

Hoping for the kind help of anyone here, thanks in advance. I have T.csh which looks like this:

#! /bin/csh

set a="01 02 03 04 05 06 07 08 09 10 11 12 13"
set b="14 15 16 17 18 19 20 21 22 23 24 25"
set c="01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25"

set X = `grep $1 EOL.txt | head -n1 | cut -d- -f1`
printf "$X\n$2\n$3\nYYYY\n1\nN\n"

The variables a,b and c are optionally used as the 3rd argument in the printf line. The problem is, whenever I try to run the script, it showed undefined variable. These set command lines are working whenever I assigned them interactively, but inside the script, it seems to not work. Perhaps I need to initialize it but could not figure out how. Just new to this programming thing, I hope someone here can help me. Thanks a lot in advance.

Here are the sample execution and error for your reference:

CAT-46{bc2}40>set a="01 02 03 04 05 06 07 08 09 10 11 12 13"
CAT-46{bc2}41>./T.csh 4773 XXXX.XX "$a"
62
XXXX.XX
01 02 03 04 05 06 07 08 09 10 11 12 13
82869
1
N
CAT-46{bc2}42>unset a
CAT-46{bc2}43>./T.csh 4773 XXXX.XX "$a"
a: Undefined variable
CAT-46{bc2}44>

If i set the variables manually,it's OK, but when I called for it from the script, its flagging undefined variable error.

Mike

Upvotes: 6

Views: 46571

Answers (2)

I post another answer because a comment is too short. Look at the following.

I have a script named /tmp/T.csh:

#!/bin/csh
set a="blah"
echo $a
  1. My shell is bash; I type /tmp/T.csh: result is blah (csh executed the script).
  2. Still in bash; I type unset a; /tmp/T.csh $a: result is the same.
  3. Still in bash; I type . /tmp/T.csh: no result (bash executed the script).
  4. I type csh; now I am in csh.
  5. I type /tmp/T.csh: result is blah (of course).
  6. I type /tmp/T.csh $a: "a: Undefined variable"
  7. set a = something
  8. /tmp/T.csh $a: blah
  9. echo $a: something
  10. unset a
  11. echo $a: "a: Undefined variable"

I replicated all you did; hope this helps. You get an error for what you wrote on the command line, not for the content of your script. Even a simple echo, as you can see here above, gives an error if you on the command line refer to a variable which does not exist.

Upvotes: 3

prompt> unset a
prompt> ./T.csh 4773 XXXX.XX "$a"

The first command, "unset a", deletes the variable. In the second command you try to read the variable (on the command line!). That is why csh complains.

Upvotes: 0

Related Questions