Zsh Mailing List Archive
Messages sorted by:
Reverse Date,
Date,
Thread,
Author
Re: why is eval needed?
- X-seq: zsh-users 28411
- From: Stephane Chazelas <stephane@xxxxxxxxxxxx>
- To: Ray Andrews <rayandrews@xxxxxxxxxxx>
- Cc: Zsh Users <zsh-users@xxxxxxx>
- Subject: Re: why is eval needed?
- Date: Sat, 19 Nov 2022 16:48:52 +0000
- Archived-at: <https://zsh.org/users/28411>
- In-reply-to: <d0ef2035-e8e9-00c5-7f53-b16609d96262@eastlink.ca>
- List-id: <zsh-users.zsh.org>
- Mail-followup-to: Ray Andrews <rayandrews@xxxxxxxxxxx>, Zsh Users <zsh-users@xxxxxxx>
- References: <d0ef2035-e8e9-00c5-7f53-b16609d96262@eastlink.ca>
2022-11-19 06:34:30 -0800, Ray Andrews:
> In a script:
>
> local level='-L 2'
> tree $level
> #eval tree $level
>
> run it:
>
> 2 /aWorking/Zsh/Source/Wk 0 $ . testing
> tree: Missing argument to -L option.
>
> If I use 'eval' it's fine.
We need eval when we need to evaluate some code stored as a
string dynamically.
For instance, in perl, you could do:
$code_to_invoke_tree = 'system("tree", ';
$code_to_represent_arguments_for_tree = '"-L", "2"';
$code = $code_to_invoke_tree .
$code_to_represent_arguments_for_tree . ');'
eval $code;
We have $code containing system("tree", "-L", "2");. That's perl
code which we evaluate with eval.
That looks very silly doesn't it?
Nobody's ever going to do that. Rather, you'd do:
$cmd = "tree";
@args_for_tree = ("-L", "2");
system($cmd, @args_for_tree);
It's exactly the same for shells except that the equivalent
syntax of perl's:
system("tree", "-L", "2");
to invoke tree with -L and 2 as arguments is:
tree -L 2
In shell, you separate arguments with whitespace instead of ",". You
don't need a system() function, because the shell's main job is
to execute commands that's the main thing it does, it would get
old quickly if had to use something like system() for everyone
of them. You don't need quotes around those arguments, because
everything is string in shells, since command arguments are
strings and that's the one thing shells deal with.
Now, you could also do:
shell_code_to_run_tree='tree '
shell_code_to_represent_arguments_for_tree='-L 2'
code=$shell_code_to_run_tree$shell_code_to_represent_arguments_for_tree
eval $code
but that would be equally silly. And like in perl you'd rather do:
cmd=tree
args_for_tree=(-L 2)
$cmd $args_for_tree
But you still need those -L and 2 to be two separate arguments,
hence the list variable.
If you do:
cmd=tree
arg='-L 2'
$cmd $arg
that's the same as:
$cmd = "tree";
$arg = '-L 2';
system($cmd, $arg);
And you're calling tree with only one "-L 2" argument while you
want to call it with 2 arguments: -L and 2.
--
Stephane
Messages sorted by:
Reverse Date,
Date,
Thread,
Author