2015-03-03 66 views
0

我正在尝试编写一个脚本,该脚本将对选定的文件进行操作。防止在bash脚本中出现globbing

#!/bin/bash 
#ytest 
lastArgNo=$# 
sPattern=${!lastArgNo} 
echo "operating on $sPattern" 
#do operation on $sPattern 
for sFile in $sPattern do 
    #do something with each file 
done 

如果我开始这个脚本 参数* .JPG我得到

operating on IMG_1282.JPG 

这是发现模式*正在处理.JPG,只有这个文件的最后一个文件。我需要命令行中给出的实际文件模式。提前致谢。

+2

在运行脚本以完全禁用路径名扩展(但在此情况下请记住在脚本中将其重新打开)之前,将脚本引用至脚本或运行'set -f'。 – 2015-03-03 14:21:42

+0

[Prevent \ *将在bash脚本中展开]的可能重复(http://stackoverflow.com/questions/2470638/prevent-to-be-expanded-in-the-bash-script) – tripleee 2015-03-03 14:38:25

+0

它不是重复的因为我无法在脚本中设置-o noglob。用引号逃脱并不能解决问题。 – 2015-03-03 15:11:52

回答

1

您无法获得实际模式:在启动脚本之前,shell已经对其进行了扩展。你得到的实际文件作为参数,所以你应该做的是遍历所有参数:

#!/bin/bash 
echo "operating on $# files" 
for file; do 
    # do something with each "$file" 
done 

你在做什么是设置lastArgNo成参数的数量,使用间接变量扩展设置sPattern到最后一个参数的值。如果你做了arg=1; sPattern=${!arg}你可以设置sPattern为第一个参数。

+0

谢谢!这样做的诀窍( - ; – 2015-03-03 16:34:37