无法在while循环中读取文件

时间:2019-05-20 12:08:19

标签: bash while-loop

我有以下代码:

#!/bin/bash

. ~/.bash_profile

dt=$(date +"%Y.%m.%d")

if [[ "$#" -eq '0' ]] || [[ "$#" -eq '1' ]]
then
echo -e "Not correct usage"
exit 1
fi

tar zvxf $SHARE/*.gz -C $SHARE/landing/

sleep 3

ops () {
//
some sets of command
//
}

while read -r line
do
if [[ "$1" == "A" ]] || [[ "$1" == "B" ]] || [[ "$1" == "C" ]] && [[ "$2" =~ "$line" ]] || [[ "$2" == "ALL" ]]
then
ops
fi
done < $SHARE/landing/dir/ApprovedList."$1"

运行脚本时,我可以看到它可以解压缩.gz文件并将其放入文件夹:$SHARE/landing/

但是我想它无法读取文件并无法执行ops函数中的操作,以下是我在交互式模式下运行脚本后获得的最后一行输出:

+ read -r line

非常欢迎任何帮助!

2 个答案:

答案 0 :(得分:2)

请显示输入格式,参数格式以及一些说明。同时,针对可读性和错误处理进行了调整-进行编辑以使其具有品味。 YMMV。

#!/bin/bash

. ~/.bash_profile

ops () {  # do some stuff
  : some sets of commands ...
}

die() {
  printf "%s\n\n Use: $0 x y z ...\n\n" "$1" >&2
  kill -term $$ # exit in function behaves like return
}

# dt=$(date +"%Y.%m.%d") # unused

case "$#" in
0|1) die "Insufficient arguments" ;;
esac

tar zvxf "$SHARE"/*.gz -C "$SHARE/landing/" || die "tar failed"

sleep 3
infile="$SHARE/landing/dir/ApprovedList.$1"
[[ -e "$infile" ]] || die "$infile does not exist"
[[ -r "$infile" ]] || die "$infile is nor readable by $0 as $LOGNAME"
while read -r line
do case "$1" in
   A|B|C) case "$2" in
          *"$line"*|ALL) ops ;;
                      *) : data does not match, skipping ;;
          esac ;;
       *) die "Invalid arg1 '$1'";;
   esac
done < "$infile"

注意:

如果您确实需要 两个参数,那么让我们检查一下:

die() {
  printf "%s\n\n Use: $0 x y\n\n" "$1" >&2
  kill -term $$ # exit in function behaves like return
}

case "$#" in
2) ;;
*) die "Incorrect # of arguments" ;;
esac

此外,比kill更好-在顶部添加trap

trap 'echo >&2 "ERROR in $0($BASH_SOURCE) at line $LINENO: [$BASH_COMMAND]"; exit $LINENO;' ERR

并在函数中使用文字错误返回。

die() {
  printf "%s\n\n Use: $0 x y\n\n" "$1" >&2
  return 1
}

答案 1 :(得分:0)

支票([[ "$2" =~ "$line" ]]除外)

if [[ "$1" == "A" ]] || [[ "$1" == "B" ]] || [[ "$1" == "C" ]] && [[ "$2" =~ "$line" ]] || [[ "$2" == "ALL" ]]

在while循环内不变。因此,最好在进入while循环之前检查一次。 因此,现在您要为ops的每一行执行$SHARE/landing/dir/ApprovedList."$1"

您可以使用

xargs -a "$SHARE/landing/dir/ApprovedList.$1" -L 1 ops

编辑: 当您对每行执行简单检查时,可以将此检查移至ops函数中。
首先保存$2,然后再输入函数:

to_be_checked="$2"
...
ops() {
   [[ "$0" =~ "${to_be_checked}" ]] && return