【问题标题】:Troubles Executing GREP/CUT Command from Bash Script从 Bash 脚本执行 GREP/CUT 命令时遇到问题
【发布时间】:2019-10-30 15:06:14
【问题描述】:

我正在尝试在 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,所以我为这个菜鸟式的问题道歉,但非常感谢任何帮助 :)

【问题讨论】:

标签: linux bash shell command-line grep


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2013-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多