【发布时间】: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,所以我为这个菜鸟式的问题道歉,但非常感谢任何帮助 :)
【问题讨论】:
-
将您的命令括在
$( ... )中,而不是引号:cmdRead=$(grep ${reader} -w /etc/passwd | cut -d: -f 1,4,5)。 -
另外,
cut中 -f 参数的值不需要引用冒号,因此不需要转义引号。请参阅我之前的评论。 -
非常感谢@AndrewVickers 我可以将您的评论标记为已接受的答案吗?
-
@CyberStems 我在下面添加了一个答案,以便您接受/投票。谢谢!
标签: linux bash shell command-line grep