Bash 如果grep找到了它要找的东西,那么做X或者Y
在此语句中,我试图匹配路径/app/$var1(应用程序名称)中是否存在版本($var2) 当前代码: 这包括我的所有代码(未清理)。 我运行的命令:“./xmoduleloadfirefox/3.6.12” 这个版本确实存在Bash 如果grep找到了它要找的东西,那么做X或者Y,bash,grep,Bash,Grep,在此语句中,我试图匹配路径/app/$var1(应用程序名称)中是否存在版本($var2) 当前代码: 这包括我的所有代码(未清理)。 我运行的命令:“./xmoduleloadfirefox/3.6.12” 这个版本确实存在 #!/bin/bash # hook for some commands #echo $@ #value of sting that is entered after "xmodule" cmd=$(basename "$0") #echo "called as $
#!/bin/bash
# hook for some commands
#echo $@ #value of sting that is entered after "xmodule"
cmd=$(basename "$0")
#echo "called as $cmd"
if [[ $cmd = "xmodule" ]]
then
realcmd='/app/modules/0/bin/modulecmd tcsh'
# verify parameters
fi
# check if $@ contains value "/" to determine if a specific version is requested.
case "$@" in
*/*)
echo "has slash"
var1=$(echo "$@" | grep -Eio '\s\w*') # Gets the aplication name and put it into var1
echo $var1 # is not printed should be "firefox"
var2=$(echo "$@" | grep -o '[^/]*$') # Gets version name and put it into var2
echo $var2
# Checking if version number exist in /app/appname/
if find /app/$var1 -noleaf -maxdepth 1 -type l -o -type d | grep $var2; then
$realcmd "$@"
exit $?
else
echo "no match, the version you are looking for does not exist"
# Should there be an exit here?
fi
;;
*)
echo "doesn't have a slash"
;;
esac
输出:
我的计算机[9:55am][user/Desktop/script]->./xmodule加载firefox/3.6.12
“有刀砍吗
3.6.12
不匹配,您要查找的版本不存在
如果有空白(3.6.1以上),则应提供应用程序名称。我现在意识到这一定是我的问题,因为它使用的路径我可能只是/app。
但我不认为我对代码的这一部分做了任何更改。来自
grep
手册:
如果找到所选行,则退出状态为0,如果未找到,则退出状态为1。如果发生错误,则退出状态为2
换句话说,紧接着你的废话废话| grep$var2
,只需检查返回值
由于管道的退出代码是该管道中最后一个进程的退出代码,因此可以使用以下代码:
find /app/$var1 -maxdepth 1 -type l -o -type d | grep $var2 ; greprc=$?
if [[ $greprc -eq 0 ]] ; then
echo Found
else
if [[ $greprc -eq 1 ]] ; then
echo Not found
else
echo Some sort of error
fi
fi
您可以使用整个grep管道作为
if
语句的条件。使用grep-q
阻止它打印找到的匹配项(除非您希望打印)。我还简化了退出(如果您要立即使用它,则无需将$?
存储在变量中)。结果如下:
if find "/app/$var1" -maxdepth 1 -type l -o -type d | grep -q "$var2"; then
$realcmd "$@"
exit $?
else
echo "no match, the version you are looking for does not exist"
# Should there be an exit here?
fi
顺便说一句,由于您将在$realcmd之后立即退出,您可以使用
exec$realcmd“$@”
将shell替换为$realcmd,而不是将$realcmd作为子进程运行。当我有grep-q时,它会转到其他位置,如果我删除“-q”,它会工作。嗯,现在我无法再让它工作了。在原始问题中发布更新的代码。您还可以exec$realcmd“$@”
并省略exit$?
entirelySee
if find "/app/$var1" -maxdepth 1 -type l -o -type d | grep -q "$var2"; then
$realcmd "$@"
exit $?
else
echo "no match, the version you are looking for does not exist"
# Should there be an exit here?
fi