ted*_*ted 7 bash shell function
我知道如何将最后一个参数传递给函数,但我想知道如何在前两个函数之后获取函数的所有参数:
例如:
function custom_scp(){
PORT=$1
USER=$2
SOURCES=`ALL_OTHER_ARGS`
scp -P $PORT -r $SOURCES $USER@myserver.com:~/
}
Run Code Online (Sandbox Code Playgroud)
所以将三个文件发送到远程home目录就好像
$ custom_scp 8001 me ./env.py ./test.py ./haha.py
Run Code Online (Sandbox Code Playgroud)
当你完成它们时,只需转移前面的那些; 还剩下什么"$@".
这具有与所有POSIX shell兼容的优点(下面使用的唯一扩展是local,并且它是一种广泛使用的,甚至可用dash).
custom_scp() {
local user port # avoid polluting namespace outside your function
port=$1; shift # assign to a local variable, then pop off the argument list
user=$1; shift # repeat
scp -P "$port" -r "$@" "${user}@myserver.com:~/"
}
Run Code Online (Sandbox Code Playgroud)
您可以使用数组切片表示法:
custom_scp() {
local port=$1
local user=$2
local sources=("${@:3}")
scp -P "$port" -r "${sources[@]}" "$user@myserver.com:~/"
}
Run Code Online (Sandbox Code Playgroud)
引用Bash手册:
${parameter:offset}
${parameter:offset:length}如果参数为
@,则结果是从偏移量开始的长度位置参数.