Search code examples
linuxbashbash-function

bash scripting case switch


I am trying to initialize a variable in a case statement in a bash script,

function cpfiles(){
case $1 in
        a) echo "a" ; source = ${HOME}/dev/a.zip ; dest = 'PROGRA~2\\a.zip';;
        b) echo "b" ; source = ${HOME}/dev/b.zip ; dest = PROGRA~2\\b.zip;;
        *) echo "INVALID MODULE !" ;;
esac

echo ${source} ${dest}
}

but I am getting this error:

[#] cpfiles a
a
bash: =: No such file or directory
bash: dest: command not found...

What am I missing?


Solution

  • Your script contains this :

    a) echo "a" ; source = ${HOME}/dev/a.zip ; dest = 'PROGRA~2\\a.zip';;
    b) echo "b" ; source = ${HOME}/dev/b.zip ; dest = PROGRA~2\\b.zip;;
    

    The problem :

    • source is a shell builtin
    • You added extra spaces before and after the = sign. You may find that easier to read, but it is not valid shell syntax.

    So instead of assigning a value to a variable named source, you are actually calling the source builtin, passing it = as an argument.

    Try this instead :

    a) echo "a" ; source=$HOME/dev/a.zip ; dest='PROGRA~2\a.zip';;
    b) echo "b" ; source=$HOME/dev/b.zip ; dest='PROGRA~2\b.zip';;
    

    Please note that the braces around HOME, while perfectly valid, are not required because there is no ambiguity where the variable name ends (/ is not valid in a variable name, so the shell stops there while parsing). Double quoting would be used by most people on the assignments, but it is not required when the assigned string contains no whitespace (even if its expanded value does).

    One last issue... In one of the cases you are single-quoting the assigned value for dest, and also escaping the backslash. This will produce a value containing two backslashes, which I assume is not what you want. Remove either the quotes or one of the backslashes.