Shell指令碼用for迴圈遍歷引數的方法技巧

2022-10-06 19:42:12 字數 1315 閱讀 2577

1.當乙個指令碼需要傳入的引數較多時,可以使用for迴圈進行引數遍歷

示例:#!/bin/bash

number=65 #定義一程式設計客棧個退出值

index=1 #定義乙個計數器

if [ -z "$1" ];then #對使用者輸入的引數做判斷,如果未輸入引數則返回指令碼的用法並退程式設計客棧出,退出值65

echo "usage:$0 + canshu"

exit $number

fiecho "listing args with \$*:" #在螢幕輸入,在$*中遍歷引數

for arg in $*

www.cppcns.comdo

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

fifor 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 + canmbnyfrd**shu"

exit $number

fifor i in $@

do echo $i

done

echo

for i in "$@"

do echo $i

done

總結

shell指令碼 for迴圈

迴圈語句 while對於要求控制迴圈次數 操作物件按數字順序編號,按特定條件執行重複操作。重複測試某個條件時,只要條件成立就會反覆執行 無限 除非強制終止,或者exit語句退出指令碼 for迴圈語句 需要指定乙個變數以及可以取值的取值列表,針對每乙個不同的取值執行相同的命令序列,直到變數值用盡,退出...

shell指令碼 迴圈

迴圈有三種for,while,until,前兩種多種語言都有,大同小異,最後那種用的少,咱們就不說了 老規矩,上來先看 塊 root localhost scripts bash ceshi.sh 12 3456 78910 root localhost scripts cat ceshi.sh b...

shell 指令碼 迴圈

shell for 迴圈參考 linux下shell的for迴圈語句 shell逐行讀取檔案的3種方法 for迴圈語法 for var in item1 item2 itemn do command donefor迴圈 路徑查詢 在 mx資料夾有檔案 check list md5result tes...