Ubuntu 环境下快速打开 MATLAB 命令行

在 Ubuntu 22.04 中安装 MATLAB 之后,使用命令行运行 MATLAB 报错:

1
2
laptop@qxh-Precision-7920-Tower:~$ matlab
matlab:未找到命令

这样每次运行 MATLAB,总是要到路径 /usr/local/MATLAB/R2024a/bin 下运行 matlab 脚本,并且再切换到原来的目录,很不方便。一种解决方案是使用 alias 命令,定义一条短语替代长的字符串命令:

1
2
Creates aliases -- words that are replaced by a command string.
Aliases expire with the current shell session unless defined in the shell's configuration file, e.g. ~/.bashrc.

根据 MATLAB 在工作站的安装目录,我定义的 alias 为:

1
alias matlab="/usr/local/MATLAB/R2024a/bin/matlab -nodesktop -nodisplay"

命令中 -nodesktop -nodisplay 表示不运行 MATLAB GUI 界面(不得不吐槽 MATLAB 在 Ubuntu 下的 GUI 太丑了)。运行这一行命令之后,如果运行 alias,就会发现我们定义的短语已经加载到当前的 bash 当中了:

1
2
3
4
5
6
7
8
9
10
laptop@qxh-Precision-7920-Tower:~$ alias
alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"'
alias egrep='egrep --color=auto'
alias fgrep='fgrep --color=auto'
alias grep='grep --color=auto'
alias l='ls -CF'
alias la='ls -A'
alias ll='ls -alF'
alias ls='ls --color=auto'
alias matlab='/usr/local/MATLAB/R2024a/bin/matlab -nodesktop -nodisplay'

此外还会看到许多我们并没有直接定义的 alias,这是因为它们是在 bash 配置文件 ~/.bashrc 中预定义的,每次运行 bash 时都会将这些命令加载进来,所以,如果希望下一次运行 bash 可以直接运行 matlab,还需要将定义的 alias 加载到 ~/.bashrc 中。

编辑完 bash 配置文件之后,运行 source 命令重新加载

1
source ~/.bashrc

就可以了。

此外,如果脚本配置文件中定义了如下语句:

1
2
3
if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi

那么可以在外部文件中 .bash_aliases 写入自定义的 aliases

可能遇到的问题

执行 source ~/.bashrc如果报错如下:

1
2
3
4
5
.bashrc (line 6): 'case' builtin not inside of switch block
case $- in
^
from sourcing file .bashrc
source: Error while reading file “.bashrc”

那么这可能是因为在 Fish 环境下执行的,退出 Fish 之后就可以了。参考 my .bashrc has a typo and I do not know how to fix it