我正在查看脚本,但无法确定发生了什么。
这是一个例子:
# Command to get the last 4 occurrences of a pattern in a file
lsCommand="ls /my/directory | grep -i my_pattern | tail -4"
# Load the results of that command into an array
dirArray=($(echo $(eval $lsCommand) | tr ' ' '\n'))
# What is this doing?
yesterdaysFileArray=($(echo ${x[@]::$((${#x[@]} / 2))} | tr ' ' '\n'))
这里发生了很多事情。我理解数组是如何工作的,但我不知道如果从未声明 $x ,它是如何被引用的。
我看到 $((${#x[@]}/2}} 正在获取元素数量并将其分成两半,并且 tr 用于创建数组。但是还发生了什么?
最佳答案
我认为最后一行是 bash
中 ${array[@]:1:2}
形式的数组切片模式,其中 array[@ ]
返回数组的内容,:1:2
采用长度为 2 的切片,从索引 1
开始。
因此,对于您的情况,尽管您将起始索引空,因为您没有指定任何长度,并且长度为数组计数的一半。
但是在 bash
中有很多更好的方法可以做到这一点,如下所示。不要使用 eval
并使用 shell 本身的内置通配符支持
cd /my/directory
fileArray=()
for file in *my_pattern*; do
[[ -f "$file" ]] || { printf '%s\n' 'no file found'; return 1; }
fileArray+=( "$file" )
done
然后做
printf '%s\n' "${fileArray[@]::${#fileArray[@]}/2}"
关于arrays - 当未提供起始索引时,bash 数组切片如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54557499/