$*和$@的内部处理是怎样的
其实我完全理解$*和$@的用法。
例如,如果我使用以下命令运行脚本: my_script *
那么, for ONE_FILE in $@ 将会真正将每个文件放入 ONE_FILE 中进行处理。
即使文件名中有空格,ONE_FILE 也将获得正确的文件名。
然而,如果在 $* 中使用 ONE_FILE,情况就不同了。
我想你们都明白其中的区别,我不需要进一步解释。
现在,我感兴趣的是如何做。
KornShell (ksh) 如何解释 my_scrpt *
然后将文件名正确传递到 $@
并将文件名传递到 $*.
例如,当 ksh 看到 my_script *
,是否将文件名一一放入数组中,
然后将数组[1][2][3]...放入$@中进行处理?
并且,当看到 $* 时,它是否只是连接
文件名1+空格+文件名2+空格+...?
我知道这可能更多地与ksh的内部编码有关。
有什么见解吗?
Actually, I am fully understand the use of $* and $@.
For example, if I run the script using: my_script *
Then, for ONE_FILE in $@ will really get each file into ONE_FILE for processing.
Even there is space(s) in the filenames, ONE_FILE will get the correct filename.
If, however, using for ONE_FILE in $*, the story is different.
I think you guys understand the difference and I do not need to go further.
Now, what I am interested is HOW.
How the KornShell (ksh) interprets the my_scrpt *
and then pass the filenames into $@ correctly
and pass the filenames into $*.
For example, when the ksh see my_script *
, does it put the filenames one by one into an array,
and then put the array[1][2][3]... into $@ for processing ?
And, when seeing $*, does it just concat
filename1+space+filename2+space+... ?
I know that this may relate more to the internal coding of ksh.
Any insight?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,差不多。
这里要认识到的一件重要的事情是,涉及两个独立的进程:调用 shell,它将
my_script *
扩展为myscript arg1 arg2 arg3
和获取数组的子进程论据。如果该子进程是ksh
(或sh
、bash
或类似的 shell),则$*
只是语法对于“get argv[1...] 作为连接字符串”,而$@
是“get argv[1...] 作为数组”的语法。还需要注意的是,$*
和$@
仅在引用时才有意义。在 bash(ksh 的近亲)中,数组变量的这种想法实际上已经得到了推广。 (也许 ksh 也做到了这一点——我大约有十年没有使用 ksh...)
在 bash 中,这会创建一个包含 3 个元素的数组,称为
a
。请注意,第一个元素包含空格:从示例中可以看出,
"${a[*]}"
连接数组,而"${a[@]}"< /code> 实际上为您提供了各个元素。
Yes, pretty much.
One important thing to realize here are that there are two separate processes involved: the calling shell, which expands
my_script *
intomyscript arg1 arg2 arg3
and the subprocess which gets the array of arguments. If that subprocess isksh
(orsh
,bash
, or a similar shell) then$*
is just syntax for "get argv[1...] as a concatenated string" while$@
is syntax for "get argv[1...] as an array". It's also important to note that$*
and$@
are only meaningfully different when quoted.In bash, a cousin of ksh, this idea of array variables has actually been generalized. (Perhaps ksh has done this too -- I haven't used ksh for about a decade...)
In bash, this creates an array of 3 elements called
a
. Note that the first element contains a space:As you can see from the example,
"${a[*]}"
concatenates the array while"${a[@]}"
actually gives you the individual elements.