首页 > 解决方案 > 为什么“grep”在使用/“/”时会出错?

问题描述

背景

我正在尝试获取使用执行的命令的 PID,sh -c并将其存储在变量中以备后用。

#!/bin/bash

execute() {
   CMDS="$1"

   # x-terminal-emulator executes the quoted text by executing 'sh -c "$CMDS"'
   # Which is why "ps ax | grep ..." is used to search for the PID that
   # matches "sh -c $CMDS"
   x-terminal-emulator -e "$CMDS" &> /dev/null 

   cmdsPID="$(ps ax | grep \"sh -c "$CMDS"\" | xargs | cut -d ' ' -f 1)"

   echo "$cmdsPID"
}

execute "apt full-upgrade -y"

⚠️ 错误

但是,在执行上述脚本时,它返回:grep: apt full-upgrade -y": No such file or directory,为什么?

标签: bashgrep

解决方案


好的,所以我显然过度考虑了我需要转义引号才能使其工作的事实。然而,这正是我不应该做的!我只需要不转义的引号就可以了。

这是因为,正如@biffen指出的那样:

"至于错误:您出于某种未知原因转义引号,使它们成为非引号,从而将三个参数传递给 grep ("sh和) -capt full-upgrade -y"告诉它计算sh文件中 " 的数量apt full-upgrade -y",并且它告诉你它找不到那个文件。

#!/bin/bash

execute() {
    CMDS="$1"

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    # x-terminal-emulator executes the quoted text by executing 'sh -c "$CMDS"'
    # Which is why "ps ax | grep ..." is used to search for the PID that
    # matches "sh -c $CMDS"
    x-terminal-emulator -e "$CMDS" &> /dev/null 

    cmdsPID="$(ps ax | grep -v "grep" | grep -v "S+" | grep "sh -c" | grep "$CMDS" | xargs | cut -d ' ' -f 1)"

    echo "$cmdsPID"
}

execute "apt full-upgrade -y"

推荐阅读