csh向数组中添加字符串,空格问题 [英] Csh adding strings to an array, whitespace troubles

查看:71
本文介绍了csh向数组中添加字符串,空格问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在用 csh 做一些基本的事情时遇到了麻烦.我有一个字符串:

I’m having trouble doing something basic with csh. I have a string:

set newCmd = "$expansionCmd –option1 –option2 …"

我正在创建这些字符串的数组,稍后我要执行:

And I’m creating an array of these strings, which I later want to execute:

set expansionCmdList = ($expansionCmdList[*] "$newCmd")   
#I also tried without quotes, e.g. just $newCmd

最后我尝试迭代并执行这些命令:

Finally I try to iterate over and execute these commands:

foreach exCmd ($expansionCmdList) 
    `exCmd`    #execute it in the shell
end 

然而问题是数组条目不是完整的字符串,而是字符串的每一部分都由空格分隔,即第一个条目只是$expansionCmd",下一个条目将是-option1"等.

However the problem is that the array entries are not the full string, but every part of the string separated by whitespace, i.e. the first entry is just "$expansionCmd", the next entry would be "—option1" etc.

为使用c shell提前道歉,我公司的代码库被它卡住了.

Apologies in advance for using c shell, my company's code base is stuck with it.

推荐答案

任何时候您要扩展整个数组并希望保持其各个元素的身份不变,您都需要 :q(对于"quoted") 修饰符扩展.否则,只要您执行诸如 set expandCmdList=($expansionCmdList[*] "$newCmd") 之类的操作,列表中所有先前的命令就会被拆分为它们的组成词,每个词现在都它自己的数组元素.简单演示:

Any time you are expanding an entire array and want to keep its individual elements' identities intact, you need the :q (for "quoted") modifier on the expansion. Otherwise, as soon as you do something like set expansionCmdList=($expansionCmdList[*] "$newCmd"), all previous commands in the list are split out into their component words, each of which is now its own array element. Simple demonstration:

% set a = ( a "b c" d )
% echo $a[2]
b c
% set a = ( $a[*] e )
% echo $a[2]
b

糟糕,在进入执行循环之前,你已经把数组搞乱了.使用 :q:

Oops, you've messed up the array before you even get to your execution loop. Things go much better with :q:

% set a = ( a "b c" d )
% set a = ( $a:q e )
% echo $a[2]
b c

您需要在 for 循环中使用相同的修饰符:

You need to use the same modifier in the for loop:

foreach exCmd ($expansionCmdList:q) 

最后,`exCmd` 尝试运行一个字面上名为exCmd"的命令,然后获取它的输出并将那个作为命令运行.您可能想要做的只是执行一个等于变量值的命令.您可能会在这里遇到更多空白问题,并且您无法通过将每个命令设为数组来解决这些问题,因为 csh 不支持数组数组.公平警告.但是如果命令没有任何引用需求,这将起作用:

Finally, `exCmd` tries to run a command literally named "exCmd", and then take its output and run that as a command. What you probably want to do is simply execute a command equal to the value of the variable. You will likely run into more whitespace woes here, and you can't solve them by making each command an array since csh doesn't support arrays of arrays. Fair warning. But if the commands don't have any quotation needs, this will work:

  $exCmd

这篇关于csh向数组中添加字符串,空格问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆