1

I have a variable in bash let say,

val="cmd arg1 arg2"

I want to split into two parts such one part is command and other part will be all the arguments (i.e. $0 & $*). How can I do this?

Sample cases it should work in:

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"

2
  • Bad idea. You shouldn't assume that all the whitespace in the string should be used for word-splitting. Commented Dec 23, 2015 at 14:04
  • @chepner Yes! I am taking quotes into count. See stackoverflow.com/questions/34437173/…. Also input of command is from bash history file Commented Dec 23, 2015 at 14:23

1 Answer 1

2

You can try something like:

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

it prints

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=="

prints

cmd:==/c/Program Files/Oracle/VirtualBox/vBoxManage.exe==  args:==--help==
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.