2

while running below command in terminal it's working fine with highlighted red and white colour matching with the pattern as per image below,

$ grep -Ff file1.txt file2.txt

Output: expected output

But when I put the same command in script as pl.sh file and run it it's not highlighting at all as above image. I am not sure what I am doing wrong! Do I need to change the script?

#!/bin/bash

# Main file:
echo -n "Choose the Main Assignment File : "
read mainfile

# Compare a file
echo -n "Choose a file to compare with : "
read comparefile

# Compare two files and highlight differences 
sudo grep -Ff "$mainfile" "$comparefile"
5
  • 3
    Your interactive shell likely has an alias that re-defines grep to use color ex. alias grep='grep --color=auto' Commented Aug 21, 2020 at 11:32
  • 1
    The command in the script is prefixed with sudo. Why?
    – Kusalananda
    Commented Aug 21, 2020 at 11:39
  • @steeldriver Sorry I am novice in Linux env, so where I need to put that alias? In the same pl.sh file or somewhere else
    – YoungBrain
    Commented Aug 21, 2020 at 12:58
  • 1
    Well bash scripts don't expand aliases by default - and neither does sudo. So you'd need to add the color option to grep explicitly ex. grep --color=always -Ff "$mainfile" "$comparefile" Commented Aug 21, 2020 at 13:00
  • @steeldriver - thanks, it's working. Great learning today.
    – YoungBrain
    Commented Aug 21, 2020 at 13:02

1 Answer 1

4

Your interactive shell likely has an alias that re-defines grep to use color when outputing to a terminal device ex. alias grep='grep --color=auto' (perhaps defined in the default ~/.bashrc file).

Bash non-interactive scripts don't expand aliases by default - and neither does sudo. So you'd need to add the color option to grep explicitly ex.

grep --color=auto -Ff "$mainfile" -- "$comparefile" 

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.