Issue
I am trying to execute the following command in a Bash script:
grep 1001 -w /etc/passwd | cut -d ':' -f 1,4,5
grep 1004 -w /etc/passwd | cut -d ':' -f 1,4,5
it works fine from the command line in Linux, and if I remove the latter portion of the pipeline it executes properly from Bash as well.
here is my script thus far:
#/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}`
the output of this code yields:
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.
I only started learning Bash yesterday so I apologize for the noob-esque question but greatly appreciate any help :)
Solution
Enclose your command in $( ... )
, not quotes. Also, no need to quote the colon as the value of the -f parameter in cut, therefore no need to escape the quotes:
cmdRead=$(grep ${reader} -w /etc/passwd | cut -d: -f 1,4,5)
Answered By - Andrew Vickers Answer Checked By - Cary Denson (WPSolving Admin)