[英]Troubles Executing GREP/CUT Command from Bash Script
我正在嘗試在 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}`
此代碼的 output 產生:
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 所以我為這個菜鳥式的問題道歉,但非常感謝任何幫助:)
@AndrewVickers 已經在評論中回答了這個問題,下面是他的答案復制/粘貼
將您的命令括在
$(... )
中,而不是引號:cmdRead=$(grep ${reader} -w /etc/passwd | cut -d: -f 1,4,5)
此外,不需要將冒號引用為
cut
中的 -f 參數的值,因此無需轉義引號。
將您的命令括在$(... )
中,而不是引號。 此外,不需要將冒號引用為 cut 中 -f 參數的值,因此無需轉義引號:
cmdRead=$(grep ${reader} -w /etc/passwd | cut -d: -f 1,4,5)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.