cshushu
cshushu

Reputation: 109

Use commands with parentheses like diff in shell script

I want to diff output from 2 commands

diff output from cat file1 and cat file2

And I found that the solution is

diff <(cat file1) <(cat file2)

However

If I put this in a shell script The parentheses cannot be recognized since it means calling sub-shell in shell script.. (I wonder if what I know is correct)

#!bin/bash
diff <(cat $1) <(cat $2)

syntax error near unexpected token `('

Is there any solution to use commands requiring parentheses in shell script ?

I've tried

 diff `<(cat $1) <(cat $2)`
 diff `<(cat $1)` `<(cat $2)`
 diff "<(cat $1) <(cat $2)"
 diff <`(`cat $1`)` <`(`cat $2`)`

but none of the above works

I used to dump output to other files and compare those files

cat $1 > out1.txt
cat $2 > out2.txt
diff -b out1.txt out2.txt

I know this could work, but I just want to know if there's any way without dumping the output to files beforehand

Upvotes: 0

Views: 463

Answers (2)

jhnc
jhnc

Reputation: 16752

If you write a script containing bash commands, you need to run it with bash, not sh. (Consider: Would you expect rm scriptfile to run the bash commands contained in the file?)

If you want something more portable, you can use FIFOs explicitly (in particular, the mkfifo command):

#!/bin/sh

mkfifo fifo1 fifo2
cat "$1" >>fifo1 &
cat "$2" >>fifo2 &
diff -b fifo1 fifo2
rm fifo1 fifo2

Upvotes: 2

Charing Lau
Charing Lau

Reputation: 72

i tried this test.sh and get the right output.

#! /bin/bash
diff <(cat $1) <(cat $2)

Upvotes: 0

Related Questions