一、shell獲取參數數量
在shell腳本中,我們可以使用$#符號來獲取傳入參數的數量。它代表的是參數個數,不包括腳本名。
#!/bin/bash echo "The number of parameters is $#"
使用示例:
$ ./test.sh 1 2 3 The number of parameters is 3
二、shell獲取集合size
另外一個常見的需求是獲取參數列表的長度,可以使用${#array[@]}來獲取。注意要加上[@],表示獲取數組所有元素的長度。
#!/bin/bash args=("apple" "banana" "peach") echo "The number of arguments is ${#args[@]}"
使用示例:
$ ./test.sh The number of arguments is 3
三、shell獲取參數個數
使用shift命令可以使參數左移,每次左移一個位置,將前面的一個參數丟棄,直到所有的參數都被處理完。
#!/bin/bash while [ "$1" != "" ]; do echo "Argument $1" shift done
使用示例:
$ ./test.sh apple banana peach Argument apple Argument banana Argument peach
四、shell獲取參數長度
可以使用${#var}獲取字元串變數的長度,也可以使用${#@}來獲取第一個參數的長度。
#!/bin/bash str="hello world" echo "String length is ${#str}" echo "Length of first argument is ${#@}"
使用示例:
$ ./test.sh apple String length is 11 Length of first argument is 5
五、shell獲取參數列表
可以使用$@來獲取所有傳入的參數列表,也可以使用${array[@]}來獲取數組中所有參數。
#!/bin/bash args=("apple" "banana" "peach") echo "Arguments are: ${args[@]}" echo "All arguments are: $@"
使用示例:
$ ./test.sh apple banana peach Arguments are: apple banana peach All arguments are: apple banana peach
六、shell獲取參數返回1
使用$?可以獲取上一個命令的返回值。
#!/bin/bash echo "This command will return 1" exit 1
使用示例:
$ ./test.sh This command will return 1 $ echo $? 1
七、shell獲取參數值
可以通過$1、$2等來獲取相應位置的參數值。
#!/bin/bash echo "First argument is $1" echo "Second argument is $2"
使用示例:
$ ./test.sh apple banana First argument is apple Second argument is banana
八、shell獲取參數最後一個
可以使用${!#}來獲取最後一個參數的值。
#!/bin/bash echo "The last argument is ${!#}"
使用示例:
$ ./test.sh apple banana peach The last argument is peach
九、shell獲取參數並寫到控制台
使用read命令可以獲取用戶輸入的參數值。
#!/bin/bash echo "Enter your name:" read name echo "Hello, $name"
使用示例:
$ ./test.sh Enter your name: John Hello, John
十、獲取多個參數選取
可以使用getopts命令來獲取多個參數並選取,使用循環讀取所有參數。
#!/bin/bash while getopts ":a:b:" opt; do case $opt in a) arg1="$OPTARG" ;; b) arg2="$OPTARG" ;; \?) echo "Invalid option: -$OPTARG" >&2 exit 1 ;; :) echo "Option -$OPTARG requires an argument." >&2 exit 1 ;; esac done echo "arg1 = $arg1, arg2 = $arg2"
使用示例:
$ ./test.sh -a apple -b banana arg1 = apple, arg2 = banana
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/159103.html