首页 > 解决方案 > 从 Bash 脚本执行 GREP/CUT 命令时遇到问题

问题描述

我正在尝试在 Bash 脚本中执行以下命令:

grep 1001 -w /etc/passwd | cut -d ':' -f 1,4,5
grep 1004 -w /etc/passwd | cut -d ':' -f 1,4,5

它在 Linux 的命令行中运行良好,如果我删除管道的后半部分,它也可以从 Bash 中正确执行。

到目前为止,这是我的脚本:

#/bin/bash

#find the group number correlated to reader and user
reader=`grep reader /etc/group | cut -d ":" -f3`
user=`grep user /etc/group | cut -d ":" -f3`

echo reader: $reader #prints 1004
echo user: $user #prints 1001

cmdRead="grep ${reader} -w /etc/passwd | cut -d \":\" -f 1,4,5"
cmdUser="grep ${user} -w /etc/passwd | cut -d \":\" -f 1,4,5"

echo executing command: ${cmdRead}
echo `${cmdRead}`
echo executing command: ${cmdUser}
echo `${cmdUser}`

此代码的输出产生:

reader: 1004
user: 1001
executing command: grep 1004 -w /etc/passwd | cut -d ":" -f 1,4,5
grep: invalid argument ‘":"’ for ‘--directories’
Valid arguments are:
  - ‘read’
  - ‘recurse’
  - ‘skip’
Usage: grep [OPTION]... PATTERN [FILE]...
Try 'grep --help' for more information.

executing command: grep 1001 -w /etc/passwd | cut -d ":" -f 1,4,5
grep: invalid argument ‘":"’ for ‘--directories’
Valid arguments are:
  - ‘read’
  - ‘recurse’
  - ‘skip’
Usage: grep [OPTION]... PATTERN [FILE]...
Try 'grep --help' for more information.

我昨天才开始学习 Bash,所以我为这个菜鸟式的问题道歉,但非常感谢任何帮助:)

标签: linuxbashshellcommand-linegrep

解决方案


将您的命令括在 中$( ... ),而不是引号中。此外,不需要将冒号引用为 cut 中 -f 参数的值,因此无需转义引号:

cmdRead=$(grep ${reader} -w /etc/passwd | cut -d: -f 1,4,5)

推荐阅读