Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pipeline | in bash usage?

Tags:

bash

I am learning BASH, my problem is the following.

I'm decompressing a file using tar -zxvf, this returns a (what I think) is a list type ls -l from the folder it has been extracted. What I want to do is take the first object of it using head -1.

I can do this, but to keep my code clean I would like to do it using pipeline.

This works:

filename_2=$(tar zxvf ${filename}) 
echo "${filename_2}" | head -1

This doesn't (it returns an empty string):

filename_2=$(tar zxvf ${filename}) | head -1
echo "${filename_2}"

Am I understanding the pipeline concept wrong? I thought that it simply took the input from the last function as input of the last one, if so, why do I need to do it in two separate lines?

Thanks

like image 726
DDDDEEEEXXXX Avatar asked Aug 05 '26 19:08

DDDDEEEEXXXX


1 Answers

You don't need the variable at all. Pass the output of tar directly to head.

tar zxvf "$filename" | head -1

If you then wanted to save that result in a variable you'd write:

filename_2=$(tar zxvf "$filename" | head -1)
echo "$filename_2"
like image 93
John Kugelman Avatar answered Aug 08 '26 12:08

John Kugelman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!