您现在的位置是:网站首页> 编程资料编程资料
Shell脚本用for循环遍历参数的方法技巧_linux shell_
                    
                
                2023-05-26
                546人已围观
            
简介 Shell脚本用for循环遍历参数的方法技巧_linux shell_
1.当一个脚本需要传入的参数较多时,可以使用for循环进行参数遍历
示例:
#!/bin/bash number=65 #定义一个退出值 index=1 #定义一个计数器 if [ -z "$1" ];then #对用户输入的参数做判断,如果未输入参数则返回脚本的用法并退出,退出值65 echo "Usage:$0 + canshu" exit $number fi echo "listing args with \$*:" #在屏幕输入,在$*中遍历参数 for arg in $* do echo "arg: $index = $arg" let index+=1 done echo index=1 #将计数器重新设置为1 echo "listing args with \"\$@\":" #在"$@"中遍历参数 for arg in "$@" do echo "arg: $index = $arg" let index+=1 done

小技巧1:在"$*"和$*中遍历参数的区别
示例:
#!/bin/bash number=11 if [ $# -eq 0 ];then echo "Usage: $0 + canshu" exit $number fi for i in $* #在$*中遍历参数,此时每个参数都是独立的,会遍历$#次 do echo $i done echo for i in "$*" #在"$*"中遍历参数,此时"$*"被扩展为包含所有位置参数的单个字符串,只遍历一次 do echo $i done

小技巧2:在"$@"和$@中遍历参数没有区别
示例:
#!/bin/bash number=11 if [ $# -eq 0 ];then echo "Usage: $0 + canshu" exit $number fi for i in $@ do echo $i done echo for i in "$@" do echo $i done

总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。如果你想了解更多相关内容请查看下面相关链接
您可能感兴趣的文章:
                
                
相关内容
- Shell脚本中awk指令的用法_linux shell_
 - Shell中字符串排序的几种方法_linux shell_
 - Shell中整数计算的几种方式_linux shell_
 - Shell中统计字符串中单词的个数的几种方法_linux shell_
 - Shell中去除字符串前后空格的方法_linux shell_
 - shell中使用expect命令进行远程执行命令脚本_linux shell_
 - shell命令实现当前目录下多个文件合并为一个文件的方法_linux shell_
 - Linux shell命令统计某列去重后的值_linux shell_
 - Linux shell脚本的建立与执行_linux shell_
 - Linux shell数组与关联数组的用法实例_linux shell_
 
                                
                                                        
                                
                                                        
                                
                                                        
    