Bash数组访问文件全局

时间:2015-07-28 17:37:05

标签: arrays bash

我是新手来编写脚本但是在访问数组时遇到问题。 (或者我认为是一个数组)我使用文件glob来获取数组的内容。

我只想打印每个文件,然后允许用户根据其索引选择一个文件。但是我注意到所有内容都存储在数组的第一个元素中。我错过了什么?文件全球化不是我想要的最好的想法吗?

files=templates/*.tex
fnum=0
for file in $files
do
        echo $fnum : $file
        # bash expression is ((expression)) $(( expression )) expects a command
        (( fnum++ ))
done
read -p "Which file would you like to include: " answer
if [ $answer -ge 0 ] && [ $answer -lt $fnum ]
then
        echo ${$files[0]}
else
        echo bad range...
        exit 1
fi

2 个答案:

答案 0 :(得分:7)

files不是数组; files=( templates/*.tex )是。

files=( templates/*.tex )
fnum=0
for file in "${files[@]}"
do
        echo "$fnum : $file"
        (( fnum++ ))
done
read -p "Which file would you like to include: " answer
if [ "$answer" -ge 0 ] && [ "$answer" -lt "$fnum" ]
then
        echo "${files[answer]}"
else
        echo bad range...
        exit 1
fi

bash中更具惯用性(不完全相同,但更简洁地提供相同的基本功能):

PS3="Which file would you like to include: "
select answer in "${files[@]}"; do
    echo "$answer"
    break
done

答案 1 :(得分:1)

你的files变量是一个字符串,试试files=( templates/*.tex )如果我没有误会这应该是一个文件数组

要遍历数组,您应该使用for file in "${files[@]}"