Passing parameters to bash script function (or subroutine)

I've found a few posts regarding passing parameters to a function or subroutine, but for some reason when I try to run a command based on part with these parameters it's not working. If I have the function echo the parameters they show correctly so I believe they are being passed right but the command fails when it runs.

#!/bin/bash

function waitforvmtools {
# this line works
  /usr/bin/vmware-cmd -H lab-esxi1 -U root -P 'pass!word' '[NFS2] lab-vcenter/lab-vcenter.vmx' gettoolslastactive
# this line should be the same but does not work
  /usr/bin/vmware-cmd -H $1 -U root -P 'pass!word' $2 gettoolslastactive
# but this shows the proper parameters being passed
echo /usr/bin/vmware-cmd -H $1 -U root -P 'pass!word' $2 gettoolslastactive

# this is what I'm ultimately trying to do with it
#  toolstate=`/usr/bin/vmware-cmd -H $1 -U root -P 'pass!word' $2 gettoolslastactive`
#  until [  "$toolstate" = "gettoolslastactive() = 1" ]; do
#    sleep 5
#    toolstate=`/usr/bin/vmware-cmd -H $1 -U root -P 'pass!word' $2 gettoolslastactive`
#    echo $toolstate
#  done
}

waitforvmtools lab-esxi1 "'[NFS2] lab-vcenter/lab-vcenter.vmx'"

Thanks for any suggestions!

h

Try quoting your variables:

/usr/bin/vmware-cmd -H "$1" -U root -P 'pass!word' "$2" gettoolslastactive

And on your call, I think you can drop the single quotes:

waitforvmtools lab-esxi1 "[NFS2] lab-vcenter/lab-vcenter.vmx"

If that doesn't work, try putting a set -x before the call to see exactly what/how the command is being expanded.

1 Like

Thank you agama, it was both that needed to be done. I wrapped the variables in quotes (it was really only the $2 that needed to be wrapped) and take the single quotes off the call.

I appreciate your help on this!

Thanks again!

h

Final code:

#!/bin/bash

function waitforvmtools {
  toolstate=`/usr/bin/vmware-cmd -H $1 -U root -P 'pass!word' "$2" gettoolslastactive`
  until [  "$toolstate" = "gettoolslastactive() = 1" ]; do
    sleep 5
    toolstate=`/usr/bin/vmware-cmd -H $1 -U root -P 'pass!word' "$2" gettoolslastactive`
  done
}

waitforvmtools lab-esxi1 "[NFS2] lab-vcenter/lab-vcenter.vmx"