shell脚本grep来grep一个字符串

Jil*_*448 5 bash grep

以下脚本的输出为空白.缺少什么?我正在尝试grep一个字符串

#!/bin/ksh    
file=$abc_def_APP_13.4.5.2    
if grep -q abc_def_APP $file; then
 echo "File Found"
else
 echo "File not Found"
fi
Run Code Online (Sandbox Code Playgroud)

Jon*_*ler 9

bash,使用<<<字符串中的重定向('Here string'):

if grep -q abc_def_APP <<< $file
Run Code Online (Sandbox Code Playgroud)

在其他shell中,您可能需要使用:

if echo $file | grep -q abc_def_APP
Run Code Online (Sandbox Code Playgroud)

我把我then放在下一行; 如果你想要你then在同一条线上,那么; then在我写完之后添加.


请注意,此作业:

file=$abc_def_APP_13.4.5.2
Run Code Online (Sandbox Code Playgroud)

很奇怪; 它获取环境变量的值${abc_def_APP_13}并添加.4.5.2到结尾(它必须是env var,因为我们可以看到脚本的开头).你可能打算写:

file=abc_def_APP_13.4.5.2
Run Code Online (Sandbox Code Playgroud)

通常,您应该将对包含文件名的变量的引用括在双引号中,以避免文件名中的空格等问题.这里并不重要,但良好实践是良好做法:

if grep -q abc_def_APP <<< "$file"
if echo "$file" | grep -q abc_def_APP
Run Code Online (Sandbox Code Playgroud)