bash 中的“echo (ls)”有什么作用?

bash 中的“echo (ls)”有什么作用?

当我echo (ls)在 bash 中运行时,它返回:

-bash: syntax error near unexpected token `ls'

我知道我应该转义括号或引号以获得纯文本输出。但如果括号意味着在子 shell 环境中运行命令序列,结果对我来说仍然没有意义。

我的环境:bash 4.3(通过自制程序安装),OS X El Capitan

答案1

它本质上是一个通用语法错误,与ls令牌没有具体关系。 bash使用 yacc 解析器,它对yyerror()任何问题调用通用的解析器,在生成的错误处理中,它继续尝试查明错误。该消息来自此块(请参阅来源):

  /* If the line of input we're reading is not null, try to find the       
     objectionable token.  First, try to figure out what token the
     parser's complaining about by looking at current_token. */
  if (current_token != 0 && EOF_Reached == 0 && (msg = error_token_from_token (current_token)))
    {
      if (ansic_shouldquote (msg))
    {
      p = ansic_quote (msg, 0, NULL);
      free (msg);
      msg = p;
    }
      parser_error (line_number, _("syntax error near unexpected token `%s'"), msg);
      free (msg);

      if (interactive == 0)
    print_offending_line ();

      last_command_exit_value = parse_and_execute_level ? EX_BADSYNTAX : EX_BADUSAGE;
      return;
    }

换句话说,它已经被 混淆了'(',并且向前查看上下文正在报告ls

A(在命令的开头是合法的,但不是嵌入的。根据手册页:

   Compound Commands                                                       
       A compound command is one of the following:

       (list) list  is  executed in a subshell environment (see COMMAND EXECU‐
              TION ENVIRONMENT below).  Variable assignments and builtin  com‐
              mands  that  affect  the  shell's  environment  do not remain in
              effect after the command completes.  The return  status  is  the
              exit status of list.

进一步阅读:

答案2

ls应该在 backtiks 内或者你应该像这样尝试:

    echo $(ls)

相关内容