将文件读入数组

moa*_*a_u 4 command-line bash

如何在 shell 脚本中读取文件,然后将每一行分配给一个我可以稍后使用的变量,(我正在考虑从文件加载默认设置的方法)

我已经尝试过:

process (){

}

FILE=''
read -p "Please enter name of default file : " FILE

if [ ! -f $FILE  ]; then

    echo "$FILE : does not exists "
    exit 1
elif [ ! -r $FILE  ]; then

    echo "$FILE : can not read "
fi

exec 0<"$FILE"
n=0
while read -r line
do
   (assign each line to an variable) 
done
Run Code Online (Sandbox Code Playgroud)

hto*_*que 10

出于配置目的,最简单的方法可能是在配置文件中以 bash 语法定义参数,然后使用. /path/to/config.

示例default.cfg

parameter_a=100
parameter_b=200
parameter_c="Hello world"
Run Code Online (Sandbox Code Playgroud)

示例script.sh

#!/bin/bash

# source the default configuration
. /path/to/default.cfg

echo $parameter_a
echo $parameter_b
echo "$parameter_c"

...
Run Code Online (Sandbox Code Playgroud)

如果您不喜欢这种方法,您还可以将这些行读入数组:

while read line
do
    array+=("$line")
done < some_file
Run Code Online (Sandbox Code Playgroud)

要访问您将使用的项目${array[index]},例如:

for ((i=0; i < ${#array[*]}; i++))
do
    echo "${array[i]}"
done
Run Code Online (Sandbox Code Playgroud)

${#array[*]}数组的大小在哪里。)

此处阅读有关 bash 中数组的更多信息。