【问题标题】:Can't find unexpected operator (Bash error)找不到意外的运算符(Bash 错误)
【发布时间】:2011-05-22 08:14:14
【问题描述】:

我创建了一个简单的 Bash 脚本,它应该在 /usr/local/{etc,lib,include...} 从输入的目录路径中创建符号链接

#!/bin/sh

input="$1"
for subdir in "etc include bin lib man share sbin"; do
   dir=$input/$subdir
   if [ -e $dir ] && [ -d $dir ]; then
      for file in $dir/*; do
         ln -s $file /usr/local/$subdir
      done
   fi
done

我得到的错误是:

user@comp:/usr/local# ./update-locallinks /usr/local/test/
[: 6: /usr/local/test/etc: unexpected operator

这就是 /usr/local/test/ 的样子:

user@comp:/usr/local# ls /usr/local/test/
bin
etc
include
lib

【问题讨论】:

  • 我不确定,但请尝试使用 dir="$input/$subdir" 而不是 dir=$input/$subdir
  • 在第二行添加set -x并粘贴输出
  • @Troydm,我试过了,但没有用,但还是谢谢!
  • 顺便说一句,这不是minimal reproducible example,而是包含一堆与问题无关的代码,这意味着我不能在不问他们的情况下指出其他人有同样的直接问题挖掘与问题本身无关的所有位。今后,请尽量使问题中包含的代码尽可能短,从而产生相同的错误。
  • (另外,这个 shell 实际上不是 bash;/bin/sh 是 POSIX sh -- 即使它链接到 bash shell,它在以 sh 名称和不提供完整的bash 语言)。

标签: linux bash unix


【解决方案1】:

始终在测试表达式中使用双引号保护您的 bash 变量:

   if [ -e "$dir" ] && [ -d "$dir" ]; then

【讨论】:

  • -e 不需要,if [ -d "$dir" ]; then 就足够了。
【解决方案2】:
for subdir in "etc include bin lib man share sbin"; do

为什么是引号?将其更改为:

for subdir in etc include bin lib man share sbin; do

否则$dir 将在第一次(也是唯一一次)迭代中包含etc include bin ...

【讨论】:

  • 虽然这并没有解决“意外操作员”错误,但这将是我的下一个错误,所以谢谢!这确实有帮助!
  • @xenagi:它确实也解决了这个错误,除非你输入一个包含空格的路径,在这种情况下你的 ln 调用也会失败(即使你在测试表达式中引用了变量)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-31
  • 1970-01-01
  • 2011-09-10
  • 2013-07-02
相关资源
最近更新 更多