簡體   English   中英

如何編寫 bash 腳本到 label 每個參數如下:

[英]How to write a bash script to label each argument like this:

$ bash argcnt.sh this is a "real live" test
is
real live

(只顯示成對的參數)

因為,我只有這樣知道:

#!/bin/bash
echo "$2"
echo "$4"

似乎您想打印給腳本的所有其他參數。 然后,您可以在$@上創建一個循環:

#!/bin/bash

# idx will be 2, 4, 6 ... for as long as it's less than the number of arguments given
for ((idx = 2; idx < ${#@}; idx += 2))
do
    # variable indirection below:
    echo "${!idx}"
done

注意:您也可以使用$#而不是${#@}來獲取$@中的元素數量。 我不知道一般人更喜歡哪一種。

如果你想要的是打印每個其他參數,從第二個開始,你可以使用shift

$ cat argcnt
#!/bin/bash
while shift; do printf '%s\n' "$1"; shift; done

$ ./argcnt this is a "real live" test foo
is
real live
foo

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM