I have the following script #!/bin/bashfile=$1cat $filen=$(cat $file | wc -l)cat $fileI use it like that cat some_file.txt | myScript.shthe first cat outputs the content of the file while the second doesn't.How can I preserve the content of the variable after the pipe?
How to preserve content of variable after pipe
bash;shell script;shell
This isn't doing what you think it's doing. The $1 is the first parameter you pass to the script but you're not actually passing any. This means that cat $file actually becomes cat alone. When not given any argument, cat will just print its input:$ echo foo | catfooSo, the first cat prints out the input, the contents of the file. The second has no input since it all has been taken by the first, so it does nothing. What you want to do is something like:myscript.sh fileThat will print out the contents of the file twice and also save the output of cat $file |wc in the variable n. If what you want is to save the contents of the file in $file, try:file=$(cat < $1)And run the script with the file name as an argument:script.sh file