Bash 脚本 - 如何填充数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15932356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:09:52  来源:igfitidea点击:

Bash script - how to fill array?

arraysbashls

提问by user1926550

Let's say I have this directory structure:

假设我有这个目录结构:

DIRECTORY:

.........a

.........b

.........c

.........d

What I want to do is: I want to store elements of a directory in an array

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

something like : array = ls /home/user/DIRECTORY

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

so that array[0]contains name of first file (that is 'a')

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

array[1] == 'b'etc.

array[1] == 'b'等等。

Thanks for help

感谢帮助

回答by Daniel Kamil Kozar

You can't simply do array = ls /home/user/DIRECTORY, because - even with proper syntax - it wouldn't give you an array, but a string that you would have to parse, and Parsing lsis punishable by law. You can, however, use built-in Bash constructs to achieve what you want :

你不能简单地做array = ls /home/user/DIRECTORY,因为 - 即使使用正确的语法 - 它不会给你一个数组,而是一个你必须解析的字符串,并且Parsingls会受到法律的惩罚。但是,您可以使用内置的 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

This small script saves the names of all the regular files (which means no directories, links, sockets, and such) that can be found in $YOUR_DIRto the array called array.

这个小脚本将所有可以在其中找到的常规文件的名称(这意味着没有目录、链接、套接字等)保存$YOUR_DIR到名为array.

Hope this helps.

希望这可以帮助。

回答by Gordon Davisson

Option 1, a manual loop:

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

Option 2, using bash array trickery:

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