0

I am working on a simple script that checks if there is .vimrc file and what is configured in that file:

    if [ "$(ls -a /root | grep .vimrc)" = ".vimrc" ]; then
    echo "The .vimrc file exists"

    if [ "$(cat /root/.vimrc | grep "colorscheme desert")" = "colorscheme desert" ]; then
    echo "colorscheme is already added in the .vimrc file"
    else
    echo "The file does not have colorscheme added"
    fi

The first if statement is working fine, I get .vimrc = .vimrc thus echo "The .vimrc file exists"

But, the second if statement just prints "The file does not have colorscheme added", but if I check that file, it has that part added:

cat /root/.vimrc | grep "colorscheme desert"

colorscheme desert

Thank you in advance!

2 Answers 2

0

Your grep test will only succeed if 1) the line is present exactly once, and 2) if the line matches exactly – e.g. it won't match if there are spaces before or after the text. (For the same reason, it also won't match if the .vimrc file uses CRLF line endings, because grep only deals with LF, so the CR will be returned as part of the result.)

Both tests are bad as a programming practice. The [ operator can do more than just string comparisons – it already has the ability to check if a file exists:

if [ -e /root/.vimrc ]; then

And the if statement can do more than just invoke [ – it can check the result of any command:

if grep -q "colorscheme desert" /root/.vimrc; then
0
0

You are right! .vimrc file does use CRLS line endings, and grep deals with the LF, thus I have this problem:

cat -A /root/.vimrc
M-oM-;M-?colorscheme desert$ 

In my script that would be:

M-oM-;M-?colorscheme desert$ = colorscheme desert

You are also right that I should use more simpler script configuration, as the one that you wrote, but I wanted to stick to this one because I am quite new in the scripting world, so I will stick to mine just for the sake of learning.

I added -o after grep to print only matched parts of the matching line

if [ "$(cat /root/.vimrc | grep -o "colorscheme desert")" = "colorscheme desert" ]; then

After I added that additional option, script started working fine.

Thank you very much for your help, and for helping me discover something new such as line endings!

Kind regards,

Belphegor

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .