Arrays Bash脚本-如何填充数组?

Arrays Bash脚本-如何填充数组?,arrays,bash,ls,Arrays,Bash,Ls,假设我有这个目录结构: DIRECTORY: .........a .........b .........c .........d 我想做的是:我想在数组中存储目录的元素 类似于:array=ls/home/user/DIRECTORY 所以数组[0]包含第一个文件的名称(即“a”) array[1]=“b”等 感谢您的帮助您不能简单地执行array=ls/home/user/DIRECTORY,因为即使使用正确的语法,它也不会给您一个数组,而是一个您必须解析的字符串。但是,您可以使

假设我有这个目录结构:

DIRECTORY:

.........a

.........b

.........c

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

类似于:
array=ls/home/user/DIRECTORY

所以
数组[0]
包含第一个文件的名称(即“a”)

array[1]=“b”


感谢您的帮助

您不能简单地执行
array=ls/home/user/DIRECTORY
,因为即使使用正确的语法,它也不会给您一个数组,而是一个您必须解析的字符串。但是,您可以使用内置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
这个小脚本将
$YOUR_DIR
中可以找到的所有常规文件(即没有目录、链接、套接字等)的名称保存到名为
array
的数组中


希望这有帮助。

选项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
选项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
然后


将等于该目录中的第一个文件。

这可能会有所帮助:。使用
for
循环遍历
ls
的返回值。这可能也很有用;目录列表中的所有这些点都有什么意义吗?没有。点只显示“子元素”。这可能也有帮助:它有效,但仅适用于文件。我还想将目录名存储到数组中(如果有),只需根据需要修改循环中的
if
,然后。
array=($(ls /home/user/DIRECTORY))
echo ${array[0]}