linux - 从 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,所以我为这个菜鸟式的问题道歉,但非常感谢任何帮助:)
解决方案
将您的命令括在 中$( ... )
,而不是引号中。此外,不需要将冒号引用为 cut 中 -f 参数的值,因此无需转义引号:
cmdRead=$(grep ${reader} -w /etc/passwd | cut -d: -f 1,4,5)
推荐阅读
- angular - 打字稿:如何访问 navigator.connection 属性
- datepicker - mat datepicker angular6中的周选择
- functional-programming - 这段代码有错误吗?
- qt - QML通过文本更改矩形的颜色
- javascript - 无法将浏览器历史记录到上一页JS
- python - 将内存中的图表对象发送到 Excel 文件
- r - 基于多个条件的子集数据框?
- javascript - React 的 setState 不会改变状态和更新组件
- java - 从 Android 中的设备 Mac 地址 (RARP) 获取 IP 地址
- scala - 从火花流中另一列的不同行派生列值