Bash Array Bulk Operations

Manipulate indexed arrays safely with quoted expansion, slice and search builtins, and mapfile ingestion so filenames with spaces survive round trips.

BashCli Tooling

Code

bashsnippet
21 lines
#!/usr/bin/env bash
set -euo pipefail

# mapfile 把命令输出按行灌进数组(含空格的文件名不碎裂)
mapfile -t files < <(printf '%s\n' 'report Q1.csv' 'notes.md' 'data set.json')

echo "count: ${#files[@]}"

# 追加与删除
files+=('todo.txt')
for i in "${!files[@]}"; do
  [[ "${files[$i]}" == notes.md ]] && unset 'files[i]'
done

# 切片与搜索
echo "first two: ${files[@]:0:2}"

# 安全展开:"$@" 语义的 "${arr[@]}" 逐元素引用
for f in "${files[@]}"; do
  printf 'processing <%s>\n' "$f"
done

Inside the snippet

set -euo pipefail puts the script into strict mode: it stops on the first failing command, treats unset variables as errors, and fails a pipeline if any stage fails.

The work is delegated to mapfile, chained so each stage’s output feeds the next.

The core lines of the flow

for i in "${!files[@]}"; do
  [[ "${files[$i]}" == notes.md ]] && unset 'files[i]'
for f in "${files[@]}"; do
  printf 'processing <%s>\n' "$f"

Interactive Tools for This Topic

FAQ

Does the script stop on the first error?
Yes — `set -euo pipefail` aborts on the first failing command, treats unset variables as errors, and fails the whole pipeline if any stage fails. Nothing continues half-broken.
Which external commands does the script rely on?
`mapfile` must be available on the PATH environment variable; everything else is shell built-in syntax.