Skip to content
Advertisement

Find if a shell variable contains specific string and comment it

I want to write a script that looks for a variable and checks if it contains exact string and comment it if exists.

I have tried using sed and grep but it hasnt worked for me yet.

My script for deleting:

JavaScript

JV_PAT contains the path were java in installed excluding the /bin

JAVA_LOC = /data/jdk1.8.0_111/bin/java

JV_PAT = /data/jdk1.8.0_111

My Output:

Deleted

The script gets executed successfully, but it doesnt delete the particular line from the file test_bash.

test_bash.sh file

JavaScript

I want to check if JAVA_HOME contains the exact string as JV_PAT and if it does comment it.

Note: It would be nice if you could help me with the script both for commenting and deleting.

Advertisement

Answer

Since you are using bash apparently, some comments on the script.

Start your script with #!/bin/bash. This will enforce the use of bash when executing the script.

JavaScript

The bash-way of doing this is to use $(..) in stead of the back-ticks. Unless you have a specific reason (for example old Bourne-shell compatibility), do not use back-ticks. Oh, and quote your variables if you use them.

JavaScript

Read the manual for sed; what you are doing below does not make sense.

JavaScript

sed -i does not produce output normally. Your variable del will therefore always be empty. Also, the exit status of sed does not depend on the fact whether a replacement has been done. sed also executes successful without any replacement done. So, testing the exit status of sed will not tell you whether ot not such a replacement has been done.

If you need to test whether a pattern is in a file, I think grep as a knee-reflex. With that, the result will be:

JavaScript

EDIT: As Léa Gris pointed out, the ${JV_PAT} may contain a /. Therefore, the sed contains a little more complex, using the # as separator instead of the /.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement