I want to write a bash script that takes in two parameters, running them as commands and dump their output into files. myscript.sh
contents:
$1 > file1.tmp
$2 > file2.tmp
This works fine for the following example:
myscript.sh 'echo Hello World' 'echo Hello World 2'
file1.tmp
now contains the text Hello World
and file2.tmp
contains text Hello World 2
However this breaks down when using a command that contains a pipe:
myscript.sh 'ls | grep stuff' 'ls | grep morestuff'
ls: cannot access |: No such file or directory
ls: cannot access grep: No such file or directory
ls: cannot access stuff: No such file or directory
ls: cannot access |: No such file or directory
ls: cannot access grep: No such file or directory
ls: cannot access morestuff: No such file or directory
It appears the pipe is being escaped because I get similar output as the first error if I for example run this:
ls \|
ls: cannot access |: No such file or directory
How can I unescape the pipe in my script?
eval "$1" >file1.tmp
etc., but I'm sure there's a better way of achieving what you want to do. Why do you need to pass in shell commands to a script to begin with? – Kusalananda Mar 07 '17 at 19:27