When writing a shell script today, one of the actions is to use the grep command to search for the specified content in a file. Specifies that the content is stored in a file, using a variable to get the contents of the file, and then uploading to the grep command.
This code is as follows:
For Target in ' cat Content.txt '
Do
grep $target test.txt >>result.txt
Done
The contents of the Content.txt text are:
"Domain \[2\]"
"Domain \[3\]"
"Domain \[4\]"
Because the last command to execute when using grep is (grep "domain \[2\]" test.txt), the double quotes are written directly in the Content.txt text. Then execute the script, the execution of the script began to be wrong, the direct execution (grep "domain \[2\]" test.txt) is able to search for content. But in the script is not the search for content, so added "Set-x" to see the executed command, showing the execution of the command is (grep "domain \[2\]" test.txt). Finally tortured for half a day, found that the original is content.txt text in the double quotation mark problem. Change to the following to execute success, by searching for content.
The contents of the Content.txt text are:
Domain \[2\]
Domain \[3\]
Domain \[4\]
Script:
For Target in ' cat Content.txt '
Do
grep "$target" Test.txt >>result.txt
Done
I thought about it and wrote another script test:
#!/bin/ksh
Set-x
grep "\" hello\ "" test.c
What this script actually simulates is that the double quotes above are used as part of the variable.
The execution results show that the command executed is:
+ grep "Hello" test.c
As seen in the above example, the surface looks like a search for Hello in test.c, but the search is actually ("Hello"), so the search is not. Similarly, for the previous example, I thought the search is (domain \[2\]), in fact, the search is ("domain \[2\]"), but ("Domain \[2\]") This is really not, so the search is not.
That is, if you put the double quotes on the content.txt to the variable, the double quotation marks are no longer caused by the content to be queried, but the double quotation marks are part of the variable. Finally, although the two see the same appearance, but the meaning is different. Hey, the shell is so magical, don't believe what you see, haha.
Description: The shell used is ksh.
A small question about variables with double quotes when grep in a shell script