-1

I have noticed a bit of a strange behaviour of $# in CSH. For example

set a=(Hello world); echo $#a

will output 2 as expected. Why does $# act differently with combination of environment variables?

echo $#PATH

will actually output PATH ignoring # I would expect it to output 1.

My guess is that this is just one of those CSH quirks. Nothing in man page about this. Can somebody explain this behaviour? (Please don't bother writing "don't use CSH" comments I wouldn't use it if I didn't have to)

J91321
  • 697
  • 1
  • 7
  • 19
  • PATH was created with setenv. Try: setenv a "Hello world". I Could not find a clause in my local csh man page about '#' behaving differently with setenv variables -- just lines describing its behavior with regular set variables. –  Oct 11 '15 at 01:12

2 Answers2

1

$#foo, where $foo is a shell array variable, yields the number of elements in the array $foo. If $foo is an ordinary non-array variable, $#foo yields 1.

csh and tcsh treat shell variables (set by the set command) quite differently from environment variables (set by the setenv command or inherited from the parent process). The value of an environment variable is always just a string (which is why $PATH, for example, needs : characters to delimit the list elements).

It would probably be more consistent for $#FOO, where $FOO is an environment variable, to yield 1 rather than expanding to the value of $FOO. In any case, the behavior doesn't seem to be documented, and you should avoid relying on it.

If you specifically want the number of directories in your path, $#path will give you that; $path is a shell array variable that's automatically tied to the value of the $PATH environment variable.

For other variables, you just have to keep track of whether a variable is a shell variable or an environment variable.

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
0

Environment variables can't be a list, only variables can, so doing $#PATH makes littles sense. It should probably be an error.

If you want to get the length of the path, you can use $#path. This will use the special $path variable.

Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146