このディレクトリ構造があるとしましょう:
DIRECTORY:
.........a
.........b
.........c
.........d
私がやりたいことは: ディレクトリの要素を配列に格納したい
何かのようなもの : array = ls /home/user/DIRECTORY
array[0]
最初のファイルの名前(つまり「a」)が含まれています
array[1] == 'b'
等
手伝ってくれてありがとう
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. You can, however, use built-in Bash constructs to achieve what you want :
#!/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
.
Hope this helps.
オプション 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