Arrays bash脚本中的数组处理
我有一个bash脚本,它当前在脚本中硬编码的大数组上循环。我想为用户添加一个选项,以提供该数组的一小部分。下面是代码的相关部分,我看到了一个问题:Arrays bash脚本中的数组处理,arrays,bash,syntax,Arrays,Bash,Syntax,我有一个bash脚本,它当前在脚本中硬编码的大数组上循环。我想为用户添加一个选项,以提供该数组的一小部分。下面是代码的相关部分,我看到了一个问题: echo "Output Options" echo $outOpts if [[ -z ${outOpts} ]] # if no subset is provided, run on full set then testFiles=( TEST1 TEST2 TEST3 ... TEST25 ) echo "Files to Parse" ec
echo "Output Options"
echo $outOpts
if [[ -z ${outOpts} ]] # if no subset is provided, run on full set
then
testFiles=(
TEST1
TEST2
TEST3
...
TEST25
)
echo "Files to Parse"
echo $testFiles
else
echo "Files to Parse"
testFiles=$outOpts
echo $testFiles
fi
for file in "${testFiles[@]}"
do
echo "in loop"
echo $file
if [[ -n $(anotherAlg --format ${input} | grep "name" | grep ${file}) ]]
then
echo ${scratchDir}
...
fi
done
${input}
是输入文件的路径,${scratchDir}
是目录的路径
在我运行的命令中:
$ ./parsingScript.sh -i /directory/to/file/to/parse.ntf -o /directory/to/output/ -s /directory/for/scratch/ > diagnosticfile.txt
这是一个完整的脚本,没有指定任何选项,所有内容都按应有的方式运行,echo语句的结果如下所示:
Output Options
Files to Parse
TEST1
in loop
TEST1
/directory/for/scratch/
如果我搜索诊断文件,我会发现下面有:
in loop
TEST2
/directory/for/scratch/
...
in loop
TEST3
/directory/for/scratch/
。。。
等等
我对bash不太熟悉,所以我惊讶地发现第一个if语句中的echo没有打印完整的数组,而只打印第一个元素。然而,它看起来好像是循环罚款
为输出选项添加标志时:
$ ./parsingScript.sh -i /directory/to/file/to/parse.ntf -o /directory/to/output/ -s /directory/for/scratch/ -outOpts "TEST3 TEST12" > diagnosticfile.txt
echo语句返回如下内容:
Output Options
TEST3 TEST12
Files to Parse:
TEST3 TEST12
in loop
TEST3 TEST12
[临时目录路径不打印]
在本例中,“in-loop”不会再次打印,因此脚本完全中断。我的输入数组没有像硬编码数组那样被访问,这是一个问题。我怀疑这是一个语法错误
我更擅长Python,我想做的Python版本是:
bigArray=[lots,of,stuff,...]
userArray=[lots,stuff]
subArray=[]
for item in userArray:
if item in bigArray:
subArray.append(item)
# subArray=[lots,stuff]
使
bigArray
成为关联数组(bash相当于python dict),以允许O(1)键查找:
#!/usr/bin/env bash
case $BASH_VERSION in ''|[0-3].*) echo "ERROR: Bash 4.0+ required" >&2; exit 1;; esac
declare -A bigArray=( ['lots']=1 ['of']=1 ['stuff']=1 )
declare -a userArray=( 'lots' 'stuff' 'and-junk-to-discard' )
declare -a subArray=( )
for item in "${userArray[@]}"; do
if [[ ${bigArray[$item]} ]]; then
subArray+=( "$item" )
fi
done
declare -p subArray
…:
如果bigArray:
中的项速度较慢。在Python中,可以使用set
更快地完成这项工作。在bash中,您应该使用一个关联数组,将数据作为键来更快地执行。你想要你要求的文字,还是更快的版本?顺便说一句,这个问题比它需要的要长得多,也更难理解。我希望最后的Python代表了您打算做的全部事情——但在理想世界中,我们只会有一个狭隘的问题,问一个特定的问题(与先前存在的重复项比较更容易,更容易理解和全面回答)……另一方面,考虑运行你的代码并修复它之前发现的问题,这是理所当然的问题。请看re:echo$foo的危险性(如果您想知道变量中的内容,declare-pfoo
更可靠,并且除了避免将*
更改为文件列表等其他不必要的行为之外,还会打印数组的全部内容,而不仅仅是它的第一个元素)。
declare -a subArray=([0]="lots" [1]="stuff")