Bash脚本 - 如何填充数组?

use*_*550 6 arrays bash ls

假设我有这个目录结构:

DIRECTORY:

.........a

.........b

.........c

.........d
Run Code Online (Sandbox Code Playgroud)

我想要做的是:我想在数组中存储目录的元素

就像是 : array = ls /home/user/DIRECTORY

所以array[0]包含第一个文件的名称(即'a')

array[1] == 'b' 等等

感谢帮助

Dan*_*zar 11

你不能简单地这样做array = ls /home/user/DIRECTORY,因为 - 即使使用正确的语法 - 它也不会给你一个数组,而是一个你必须解析的字符串,并且Parsing ls会受到法律的惩罚.但是,您可以使用内置的Bash构造来实现您的目标:

#!/usr/bin/env bash

readonly YOUR_DIR="/home/daniel"

if [[ ! -d $YOUR_DIR ]]; then
    echo >&2 "$YOUR_DIR does not exist or is not a directory"
    exit 1
fi

OLD_PWD=$PWD
cd "$YOUR_DIR"

i=0
for file in *
do
    if [[ -f $file ]]; then
        array[$i]=$file
        i=$(($i+1))
    fi
done

cd "$OLD_PWD"
exit 0
Run Code Online (Sandbox Code Playgroud)

这个小脚本保存了可以在$YOUR_DIR所调用的数组中找到的所有常规文件的名称(这意味着没有目录,链接,套接字等)array.

希望这可以帮助.


Gor*_*son 6

选项1,手动循环:

dirtolist=/home/user/DIRECTORY
shopt -s nullglob    # In case there aren't any files
contentsarray=()
for filepath in "$dirtolist"/*; do
    contentsarray+=("$(basename "$filepath")")
done
shopt -u nullglob    # Optional, restore default behavior for unmatched file globs
Run Code Online (Sandbox Code Playgroud)

选项2,使用bash数组技巧:

dirtolist=/home/user/DIRECTORY
shopt -s nullglob
contentspaths=("$dirtolist"/*)   # This makes an array of paths to the files
contentsarray=("${contentpaths[@]##*/}")  # This strips off the path portions, leaving just the filenames
shopt -u nullglob    # Optional, restore default behavior for unmatched file globs
Run Code Online (Sandbox Code Playgroud)