[英]Bash script: expansion of argument not using $@ or $*
使用$@
您可以對bash中的文件列表執行操作。 例:
script.sh:
#!/bin/bash
list=$@
for file in $list; do _commands_; done
然后我可以用這個程序調用
~/path/to/./script dir1/{subdir1/*.dat,subdir2/*}
這個參數將擴展為許多成為$list
的參數。 但現在我想要其他參數,比如1美元,2美元,這個名單是3美元。 所以我想在腳本中發生dir1/{subdir1/*.dat,subdir2/*}
擴展,而不是成為很多參數。 在命令行上,您可以執行以下操作:
find dir1/{subdir1/*.dat,subdir2/*}
並獲得所需的輸出,即文件列表。 所以我嘗試過這樣的事情:
arg1=$1
arg2=$2
list=$(find $3)
for file in $list; do _commands_; done
...
電話:
~/path/to/./script arg_1 arg_2 'dir1/{subdir1/*.dat,subdir2/*}'
但沒有成功。 關於如何將此列表擴展為腳本內的變量的一些幫助將非常感激!:)
編輯:所以下面的答案給出了使用這些命令的解決方案:
arg1="$1"
arg2="$2"
shift 2
for f in "$@"; do echo "processing $f"; done;
但出於好奇,是否仍然可以將字符串dir1/{subdir1/*.dat,subdir2/*}
傳遞給腳本內的find
命令(或任何指向同一端的方法),而不使用$@
,並獲取列表那樣? 這可能是有用的,例如,如果最好使列表不是第一個或最后一個參數,或者在某些其他情況下,即使它需要轉義字符或引用參數。
您可以在腳本中使用此代碼:
arg1="$1"
arg2="$2"
shift 2
for f in "$@"; do echo "processing $f"; done;
然后將其稱為:
~/path/to/script arg_1 arg_2 dir1/{subdir1/*.dat,subdir2/*}
使用shift 2
將位置參數移動2個位置,從而使$3
為$1
, $4
為$2
等。然后您可以直接調用$@
來迭代其余參數。
按照help shift
:
shift: shift [n]
Shift positional parameters.
Rename the positional parameters $N+1,$N+2 ... to $1,$2 ... If N is
在調用腳本之前,shell將執行shell擴展。 這意味着你必須引用/轉義參數。 在腳本中,您可以使用eval
執行擴展。
#!/bin/bash
arg1="$1" ; shift
arg2="$2" ; shift
eval "list=($@)"
for q in "${list[@]}" ; do echo "$q" ; done
$ ./a 123 456 'a{b,c}' 'd*'
ab ac d.pl docs
我沒有看到在您的示例中在腳本內部進行擴展的重點。
#!/bin/bash
arg1="$1" ; shift
arg2="$2" ; shift
list=("$@")
for q in "${list[@]}" ; do echo "$q" ; done
要不就
#!/bin/bash
arg1="$1" ; shift
arg2="$2" ; shift
for q in "$@" ; do echo "$q" ; done
$ ./a 123 456 a{b,c} d*
ab
ac
d.pl
docs
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.