Can we do grep and sed from a file and push the output into a variable

grep "^/dev/disk/by-id/scsi-*" /tmp/disks.txt | sed '{'s/=.*//'}'

Output would be like this:



[/~]# grep "^/dev/disk/by-id/scsi-*" /tmp/disks.txt | sed {'s/=.*//'} >> $x
-bash: $x: ambiguous redirect

Can we push all 3 lines into a variable and call them with foreach? Thanks!

1 Answer 1


I have tested, and both the below work in bash shell:

x=`grep "^/dev/disk/by-id/scsi-*" /tmp/disks.txt | sed {'s/=.*//'}`
x=$(grep "^/dev/disk/by-id/scsi-*" /tmp/disks.txt | sed {'s/=.*//'})

Notice first line is backticks, not single quotes.

The >> character in your question sends output to files, not variables.

To answer second part, yes, using output from above, a for loop works:

for line in $x 
  echo $line
  • Thanks very much for the response! I tried both methods. No go. Here is what I see : <br>[root@localhost ~]# x=$(grep "^/dev/disk/by-id/scsi-" /tmp/del.txt | sed {'s/=.//'}) <br/> [root@localhost ~]# $x -bash: /dev/disk/by-id/scsi-3644a8420420897001f2af8cc054d33bb: Permission denied <br/> [root@localhost ~]# x=$(grep "^/dev/disk/by-id/scsi-*" /tmp/del.txt | sed {'s/=.*//'}) <br/> [root@localhost ~]# $x -bash: /dev/disk/by-id/scsi-3644a8420420897001f2af8cc054d33bb: Permission denied
    – Jacky
    May 24, 2017 at 6:17
  • Sorry for the messy log snip. it is giving this error -- -bash: /dev/disk/by-id/scsi-3644a8420420897001f2af8cc054d33bb: Permission denied or -bash: /dev/disk/by-id/scsi-3644a8420420897001f2af8cc054d33bb,1171becbace78: No such file or directory
    – Jacky
    May 24, 2017 at 6:24
  • @Jes it looks like you are trying to execute $x. Don't do that; it's data, not a command. If you want to see what $x contains, use echo "$x". May 24, 2017 at 7:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.