bash: [: 参数太多?

Zab*_*bba 9 bash scripts bashrc

我正在尝试创建一个目录并cd进入其中:

在 ~/.bashrc 中:

function abc() {
  appname=$1
  appdir="$HOME/code/$appname"
  if [ mkdir $appdir -a cd $appdir ]; then
    echo Success
  else
    echo Failed to create and switch directory
  fi
}
Run Code Online (Sandbox Code Playgroud)

当我重新加载 bashrc ( . ~/.bashrc) 时,出现错误:

bash: [: too many arguments
Failed to create and switch directory
Run Code Online (Sandbox Code Playgroud)

我该如何解决?又是什么[:错误是什么意思?

附言。有人可以指导我阅读“非神秘”的 bash 脚本教程吗?

enz*_*tib 13

脚本中的主要错误是该[命令相当于testcommand,用于测试条件,例如字符串比较、文件是否存在等。

要测试您必须使用if而无需使用的进程的退出状态[,因此您的脚本可以是

if mkdir "$appdir" && cd "$appdir"; then
  echo "Success"
else
  echo "Failed to create and switch directory"
fi
Run Code Online (Sandbox Code Playgroud)

这在Bash Pitfalls: 9. if [grep foo myfile .

我建议您阅读GrayCat Bash 指南以了解 bash。