我在bash中有一个变量,比如说,
val="cmd arg1 arg2"
我想分成两部分,一部分是命令,另一部分是所有参数(即$0
& $*
)。我怎么能这样做?
它应该适用的示例案例:
val =“/ c / Program \ Files / Oracle / VirtualBox / vBoxManage.exe --help -ds”
val =“'/ c / Program Files / Oracle / VirtualBox / vBoxManage.exe' - help -ds”
val ='“/ c / Program Files / Oracle / VirtualBox / vBoxManage.exe” - help -ds'
val =“../ run dsa”
val =“/ fdfds / fds fds”
答案 0 :(得分:3)
您可以尝试以下内容:
while read -r val
do
echo "The input val is:==$val=="
declare -a 'arr=('"$val"')'
cmd=${arr[0]}
echo "Command is: ==$cmd=="
unset arr[0]
for arg in "${arr[@]}"
do
echo " argument is: ==$arg=="
done
echo
done <<EOF
cmd arg1 arg2
cmd "arg1 1" "arg2 2"
"../so me/cmd md" arg1 arg2
"../so me/cmd md" arg1 "arg2 2"
EOF
打印
The input val is:==cmd arg1 arg2==
Command is: ==cmd==
argument is: ==arg1==
argument is: ==arg2==
The input val is:==cmd "arg1 1" "arg2 2"==
Command is: ==cmd==
argument is: ==arg1 1==
argument is: ==arg2 2==
The input val is:=="../so me/cmd md" arg1 arg2==
Command is: ==../so me/cmd md==
argument is: ==arg1==
argument is: ==arg2==
The input val is:=="../so me/cmd md" arg1 "arg2 2"==
Command is: ==../so me/cmd md==
argument is: ==arg1==
argument is: ==arg2 2==
e.g。
val='"/c/Program Files/Oracle/VirtualBox/vBoxManage.exe" --help'
declare -a 'arr=('"$val"')'
cmd=${arr[0]}
unset arr[0]
args="${arr[@]}"
echo "cmd:==$cmd== args:==$args=="
打印
cmd:==/c/Program Files/Oracle/VirtualBox/vBoxManage.exe== args:==--help==