我的bash脚本中的结构错误:无法使用通配符正确列出目录中的文件

时间:2018-04-28 21:50:11

标签: linux bash shell

我会简短地忽略一些具体的实施细节。这里是初学者代码,它有三种情况:1。没有参数,从用户输入读取2.两个参数3.错误:

path="$(pwd)"
TIME_OUT="2s"
matchfile=""
reference=""
# CASE 1 : if no parameter, read from user input
if [ $# -eq 0 ]; then
# User input(detail neglected) gives the value of array[i], matchfile is test__xx
# reference is ex_xx, same as the following situation
    matchfile="test_${array[i]}"
    reference="ex_${ref}"

#if there are two parameters, matchfile is test__xx
# reference is ex_xx
# CASE 2:
elif [ $# -eq 2 ] && [ -n "$1" ] && [ -d "$2" ]; then
matchfile="test_$1"
reference="ex_$1"
#exit in other cases
#CASE 3:
else
  exit 1
fi 

这是我在目录中列出文件的部分,找到具有相同模式的文件:

set -x
echo "$path"
ls "$path"/testcases
for Y in "$path"/testcases/* ; do
  echo " Original Ref: $Y"
  if [ "$Y" == "${path}/testcases/$reference" ]; then
    ref_file="$Y"
    break

  fi
done
exit 1

现在在案例2中,file_listing代码将给出正确的消息,例如:

+ echo DIR
+ ls DIR/testcases
++ pwd
+ for Y in '"$path"/testcases/*'
+ ls DIR/testcases/2.txt
+ echo 'the directory is DIR/testcases/2.txt'
++ pwd
+ echo ' Original Ref: DIR/testcases/2.txt'
+ '[' DIR/testcases/2.txt == DIR/testcases/ex_SOMEFILE2 ']'
+ for Y in '"$path"/testcases/*'
+ ls DIR/testcases/ex_SOMEFILE2
+ echo 'the directory is DIR/testcases/ex_SOMEFILE2'
++ pwd
+ find DIR/testcases -type f -exec chmod a+rwx '{}' ';'
+ echo ' Original Ref: DIR/testcases/ex_SOMEFILE2'
+ '[' DIR/testcases/ex_SOMEFILE2 == DIR/testcases/ex_SOMEFILE2 ']'
+ ref_file=DIR/testcases/ex_SOMEFILE2
+ break
+ exit 1

在Case1中,file_listing消息变为一行:

+ echo DIR
+ ls DIR/testcases
++ pwd
+ for Y in '"$path"/testcases/*'
+ ls 'DIR/testcases/*'
ls: cannot access DIR/testcases/*: No such file or directory
+ echo 'the directory is DIR/testcases/*'
++ pwd
+ echo ' Original Ref: DIR/testcases/*'
+ '[' 'DIR/testcases/*' == DIR/testcases/ex_SOMEFILE2 ']'
+ exit 1

这意味着,通配符不起作用,但我真的不知道为什么。

0 个答案:

没有答案
相关问题