1833926 Members
2958 Online
110063 Solutions
New Discussion

Re: KSH cmd var problem?

 
SOLVED
Go to solution
Robin Abecasis
Advisor

KSH cmd var problem?

Hi,

Come across this interesting situation, which no-one at my company is able to help with, so hoping one of you nice people can help...

From a KSH command line, the following command works as expected, output goes to the screen.

echo "This is a test" >&1

However, if you re-write it as follows, then the results are not the same, infact a file named '&1' is created.

X="&1"; echo "This is a test" >${X}

Why doesn't it work, and is there some way to make it work?

Cheers in advance,
Robin Abecasis
Wots going on 'ere then?
5 REPLIES 5
Rodney Hills
Honored Contributor

Re: KSH cmd var problem?

ksh as well as other shells, do a one pass evaluation of the command line. Variables are substitued first, then the commands are executed.

You would need to supply an "eval" somewhere to make it work.

-- Rod Hills
There be dragons...
A. Daniel King_1
Super Advisor

Re: KSH cmd var problem?

Perhaps:

X="1"; echo "This is a test" >&${X}

There is something specific about the behavior of the varaible in this position. I believe that the > and & characters form a token of sorts - the same kind of token that > and $ don't.
Command-Line Junkie
Rodney Hills
Honored Contributor
Solution

Re: KSH cmd var problem?

To make it work-

x="&1"
eval "echo 'This is a test' >$x"

-- Rod Hills
There be dragons...
Robin Abecasis
Advisor

Re: KSH cmd var problem?

Many thanks for the solution, and it works for both files and screen. You're a star! :)

Cheers,
Robin
Wots going on 'ere then?
Alan Riggs
Honored Contributor

Re: KSH cmd var problem?

To answer the question "why?"

The shell (ksh, sh) interprets commands in a well-defined sequence:
Parse the line
Verbose trace
Parameter substitution
Command substitution
I/O redirection
IFS processing
Filename expansion
Execution trace
Run the command

You might think that because I/O redirection comes after parameter substitution, this would make your original statement work, but the key is that '&' is a special character which the shell marks during the initial line parse. This happens before the parameter substitution, so by the time you get to I/O redirection the '&1' is just another string to teh shell, not a stream file descriptor.

This ends my uncrontrollable pedantism for today. Please return to you rregularly scheduled lives.