Prevent globbing in a bash script

走远了吗. 提交于 2019-12-09 03:45:49

问题


I am trying to write a script that will operate on selected files.

#!/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

If I start this script with Parameters *.JPG I get

operating on IMG_1282.JPG

which is the last file found for pattern *.JPG and only this file is being processed. I need the actual file pattern that is given on the commandline. Thanks in advance.


回答1:


You cannot get the actual pattern: the shell has already expanded it before launching your script. You do get the actual files as arguments, so what you should be doing is iterating over all the arguments:

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

What you are doing is setting lastArgNo to the number of args, the using indirect variable expansion to set sPattern to the value of the last argument. If you did arg=1; sPattern=${!arg} you would set sPattern to the first argument.



来源:https://stackoverflow.com/questions/28833856/prevent-globbing-in-a-bash-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!