arrays - 当未提供起始索引时,bash 数组切片如何工作?

标签 arrays bash scripting

我正在查看脚本,但无法确定发生了什么。

这是一个例子:

# 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/

相关文章:

bash - 搜索字符串,如果匹配则添加

scripting - 关于windows批处理文件的奇怪问题

python - 尽可能快地旋转大型阵列

c++ - 堆栈溢出 Visual C++,可能是数组大小?

python - 结合 shell 和 python 代码

linux - 扩展 bash 变量,但不扩展它包含的变量

c - 将一个数组存储在另一个数组中 C

javascript - 根据数组中的值动态更改 CSS

bash - 如何将文件名从 unicode 转换为 ascii

linux - 我无法从 'script2.sh' 运行 'script1.sh'(它们在同一文件夹中并具有 755 权限)