如何解决在shell脚本参数中如何处理“-”?
| 这个问题分为3个部分,每个部分都很容易,但结合起来并不容易(至少对我来说是这样):) 需要编写一个脚本,应将其参数作为参数: 另一个命令的名字 该命令的几个参数 文件清单 例子:./my_script head -100 a.txt b.txt ./xxx/*.txt
./my_script sed -n \'s/xxx/aaa/\' *.txt
等等。
由于某些原因,我需要在脚本中进行区分
命令是什么
该命令的参数是什么
有哪些文件
因此,编写上述示例的最标准方法可能是:
./my_script head -100 -- a.txt b.txt ./xxx/*.txt
./my_script sed -n \'s/xxx/aaa/\' -- *.txt
问题1:这里有更好的解决方案吗?
在./my_script中进行处理(首次尝试):
command=\"$1\";shift
args=`echo $* | sed \'s/--.*//\'`
filenames=`echo $* | sed \'s/.*--//\'`
#... some additional processing ...
\"$command\" \"$args\" $filenames #execute the command with args and files
当filenames
包含spaces
和/或\'-\'时,此解决方案将失败。
/ some--路径/到/更多/惯用文件名.txt
问题2:如何适当地使ѭ5和ѭ6和ѭ7获得以后执行?
问题3:-如何实现以下执行方式?
echo $filenames | $command $args #but want one filename = one line (like ls -1)
这里是不错的shell解决方案,还是需要使用例如perl?
解决方法
首先,听起来您正在尝试编写一个包含命令和文件名列表并依次对每个文件名运行命令的脚本。这可以在bash的一行中完成:
$用于a.txt文件中的文件b.txt ./xxx/*.txt;执行-100 \“ $ file \”;完成
$用于* .txt中的文件;做sed -n \'s / xxx / aaa / \'\“ $ file \”;完成
但是,也许我误解了您的意图,所以让我单独回答您的问题。
代替使用\“-\”(已经具有不同的含义),下面的语法对我来说更自然:
./my_script -c \“ head -100 \” a.txt b.txt ./xxx/*.txt
./my_script -c \“ sed -n \'s / xxx / aaa / \'\” * .txt
要提取bash中的参数,请使用
getopts
:
SCRIPT=$0
while getopts \"c:\" opt; do
case $opt in
c)
command=$OPTARG
;;
esac
done
shift $((OPTIND-1))
if [ -z \"$command\" ] || [ -z \"$*\" ]; then
echo \"Usage: $SCRIPT -c <command> file [file..]\"
exit
fi
如果要为其余每个参数运行一个命令,则如下所示:
for target in \"$@\";do
eval $command \\\"$target\\\"
done
如果您想从STDIN中读取文件名,则它看起来像这样:
while read target; do
eval $command \\\"$target\\\"
done
,引号中的$@
变量将能够对参数进行分组,如下所示:
for parameter in \"$@\"
do
echo \"The parameter is \'$parameter\'\"
done
如果给出:
head -100 test this \"File name\" out
将打印
the parameter is \'head\'
the parameter is \'-100\'
the parameter is \'test\'
the parameter is \'this\'
the parameter is \'File name\'
the parameter is \'out\'
现在,您所要做的就是解析循环。您可以使用一些非常简单的规则:
第一个参数始终是文件名
以短划线开头的参数是参数
在\“-\”之后,或者一旦不是以\“-\”开头,其余都是文件名。
您可以使用以下命令检查参数中的第一个字符是否为破折号:
if [[ \"x${parameter}\" == \"x${parameter#-}\" ]]
如果您以前没有看过这种语法,则为左过滤器。 #
将变量名分为两部分。第一部分是变量的名称,第二部分是要过滤的全局过滤器(不是正则表达式)。在这种情况下,它是一个破折号。只要该语句不正确,您就知道您有一个参数。顺便说一句,在这种情况下可能需要或可能不需要ѭ19。运行测试时,如果您输入的字符串中带有破折号,则该测试可能会将其误认为是测试的参数而不是值。
放在一起将是这样的:
parameterFlag=\"\"
for parameter in \"$@\" #Quotes are important!
do
if [[ \"x${parameter}\" == \"x${parameter#-}\" ]]
then
parameterFlag=\"Tripped!\"
fi
if [[ \"x${parameter}\" == \"x--\" ]]
then
print \"Parameter \\\"$parameter\\\" ends the parameter list\"
parameterFlag=\"TRIPPED!\"
fi
if [ -n $parameterFlag ]
then
print \"\\\"$parameter\\\" is a file\"
else
echo \"The parameter \\\"$parameter\\\" is a parameter\"
fi
done
,问题1
我不这么认为,至少如果您需要对任意命令执行此操作,则不会。
问题3
command=$1
shift
while [ $1 != \'--\' ]; do
args=\"$args $1\"
shift
done
shift
while [ -n \"$1\" ]; do
echo \"$1\"
shift
done | $command $args
问题2
与问题3有何不同?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。