3

I want to write a convenience function which loads all the matlab scripts it's passed on the command line. The syntax would look like

fmatlab myscript1.m myscript2.m ... mystriptN.m

I can easily do some preset number of scripts. For instance, if I give it just a single script:

function fmatlab () { 
         $MYMATLABPATH/matlab -r "edit "$1"" &
}

Or, for two scripts:

function fmatlab () { 
         $MYMATLABPATH/matlab -r "edit "$1" "$2"" &
}

and so on. The first opens matlab, then the single script it's passed in the editor and the second opens matlab then both of the two scripts it's passed. Both these cases are checked.

But I can't do a variable number of scripts. For instance, the seemingly obvious extension

function fmatlab () { 
         $MYMATLABPATH/matlab -r "edit "$@"" &
}

opens only the first script and none of the others. I checked to make sure the command in the first quote set was the same for the two script case:

function fmatlab_echo () { 
         echo "edit "$1" "$2"" 
         echo "edit "$@""
}

and I get

$ fmatlab_echo script1.m script2.m
edit script1.m script2.m
edit script1.m script2.m

I am probably missing something basic about either $@, & (go to the next line of the terminal), or matlab -r or any combination of the three.

  • Should the edit command have quotes around each filename? Like edit "script1.m" "script2.m" etc? Or is it OK without quotes? – glenn jackman Aug 31 '17 at 18:29
  • @glennjackman it's OK without. I usually call positional variables with the quotes to avoid leaving out spaces, but that's probably unimportant in this case... – ALB Aug 31 '17 at 18:31
  • In this case, you are embedding double quotes in a double quoted string which doesn't work like you think it does. – glenn jackman Aug 31 '17 at 18:33
  • @glennjackman I tried using matlab -r "edit $@" and am faced with the same problem... – ALB Aug 31 '17 at 18:35
3

Looks like you want:

fmatlab () { 
    $MYMATLABPATH/matlab -r "edit $*" &
}

When $* is used inside double quotes, it joins all the parameters using a space (by default).

  • Success! The ironic part is I actually looked up an old question on the difference between $@ and $* and decided it probably wasn't relevant! Will I ever learn?? Thanks, man :-) – ALB Aug 31 '17 at 18:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.