如何解析文本文件中的值并将其分配给 shell 脚本参数

how to parse values from text file and assign it for shell script arguments

我在sample.txt

中存储了一些参数值
1 >> sample.txt
2 >> sample.txt
3 >> sample.txt

我已尝试解析 shell 脚本文件中的 sample.txt 以收集值并将值分配给特定变量。

   #!/bin/sh     
   if [ -f sample.txt ]; then

   cat sample.txt | while read Param

   do

   let count++
   if [ "${count}" == 1 ]; then

   Var1=`echo ${Param}`

   elif [ "${count}" == 2 ]; then

   Var2=`echo ${Param}`

   else

   Var3=`echo ${Param}`

   fi

   done

   fi


echo "$Var1"
echo "$Var2"

echo 结果不打印任何内容。我希望应该打印 1 和 2。有人帮忙吗?

你是 运行 子 shell 中的 while 循环;使用输入重定向而不是 cat:

while read Param; do
  ...
done < sample.txt

(还有,Var1=$ParamVar1=$(echo $Param)简单多了。)

但是,如果您提前知道要设置多少个变量,那么使用 while 循环就毫无意义;直接使用正确数量的 read 命令即可。

{ read Var1; read Var2; read Var3; } < sample.txt