2

I want to put the output of command in bash variable and then further use that variable in other command

Suppose i want something like this

ls | $(variable) |awk '/$variable/{print "here"}'

1
  • 1
    you need a better example problem. The current one doesn't make any sense. We really need to see 1. sample input, 2. required output, 3. actual output, 4. code that you've tried to solve a real problem. Good luck. Commented Feb 1, 2013 at 4:15

4 Answers 4

2

To put command output into variable you can use following format in bash

variable=`pwd`
echo $variable
Sign up to request clarification or add additional context in comments.

Comments

0

You can try:

variable=$(ls); awk "/$variable/"'{print "here"}'

Note 1: /$variable/ is surrounded by double quotes, otherwise it won't be replaced by output of command.

Note 2: The above command may fail since the output of ls may contains "/" or newline, which will break the awk command. You may change ls to something like ls | tr '\n' ' ' | tr -d '/' | sed 's/ *$//g'(replace all newlines with spaces; delete all slashes; remove the trailing whitespace), depending on your goal.

Note 3: to avoid variable assignment polluting the current shell's environment, you can wrap the above command by parentheses, i.e. (variable=$(some_command); awk "/$variable/"'{print "here"}')

Comments

0

I don't know that you can easily do it in a single step like that, but I don't know why you'd pipe it to awk and use it in the script like that anyway. Here's the two step version, but I'm not really sure what it does:

variable=$(ls)
echo ${variable} | awk "/${variable}/{printf \"here\"}"

2 Comments

Acutally i would like to do it in single line. is there any way
Well, you could put a ;. Why does it need to be a single pipeline?
0

Or

now=`date`

Back ticks

Which is easier for me since it works in any shell or perl

1 Comment

Backticks are equivalent to modern $(command substitution) syntax in the trivial case, but are less easy to use in the nontrivial case. The argument that they work in Perl too is a poor consolation when you run into complications. This syntax is obsolescent in the shell for a reason.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.