3

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?

dtmland
  • 508
  • 2
    You would have to 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
  • @Kusalananda I actually don't need to - the script was just an example to describe the behavior that I didn't understand. A description of eval clarifies why - the goal attempting to be achieved in the script requires the strings to be parsed twice? – dtmland Mar 07 '17 at 21:49

1 Answers1

2

You're passing a piece of shell code into the script. To the script, this is just text. For it to be interpreted as a full-blown shell command, you will have to eval it:

eval "$1" >file1.tmp
eval "$2" >file2.tmp

This works when $1 and $2 are simple things like echo hello because they are simple commands (not lists or compound commands).

An analogy with another programming language would be if you passed a piece of C code into a C program as a text string. The code would have to be compiled (and linked) somehow before it could be executed as part of the program.

Kusalananda
  • 333,661