[英]Bash script - how to fill array?
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感谢帮助
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 ls
is punishable by law .你不能简单地做
array = ls /home/user/DIRECTORY
,因为 - 即使使用正确的语法 - 它不会给你一个数组,而是一个你必须解析的字符串,并且解析ls
会受到法律的惩罚。 You can, however, use built-in Bash constructs to achieve what you want :但是,您可以使用内置的 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_DIR
to the array called array
.这个小脚本将可以在
$YOUR_DIR
找到的所有常规文件的名称(这意味着没有目录、链接、套接字等) $YOUR_DIR
到名为array
。
Hope this helps.希望这可以帮助。
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
array=($(ls /home/user/DIRECTORY))
Then然后
echo ${array[0]}
will equal to the first file in that directory.将等于该目录中的第一个文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.