Bourne shell脚本阅读文件

时间:2016-06-03 01:40:55

标签: shell unix sh

这个简单的程序应该读取文件行,而是输出" cat"每次。有什么问题?

#!/bin/sh
while read line
do
  echo $line
done <file

修改

从终端调用程序时,

file应该是用户输入文件。喜欢:

./programname file 

1 个答案:

答案 0 :(得分:3)

  

这被认为是调用程序时的用户输入文件   从终端。像:./programname file

在这种情况下你应该做

#!/bin/sh
if [ -f "$1" ] # checking if file exist
then 
 while read line
 do
   echo "$line"
 done <"$1" # double quotes important to prevent word splitting
else
  echo "Sorry file $1 doesn't exist"
fi

此处$1表示您传递给脚本的第一个参数。

有趣的读物:

  1. 什么是[ word splitting ]
  2. Shell脚本[ parameters ]
相关问题