Hello, nixcraft forums!
Is there a way to combine if and grep, so that if executes a command if grep finds a matching string in a file? If yes, can you show me the syntax?
Hello, nixcraft forums!
Is there a way to combine if and grep, so that if executes a command if grep finds a matching string in a file? If yes, can you show me the syntax?
grep command return exit status 0 if match found if not then exit status 1
you can use grep and if
ex.
HTML Code:#!/bin/bash read -p "Please enter Username to check user exist or not:- " USERNAME grep $USERNAME /etc/passwd 2>&1 >/dev/null if [ $? -eq 0 ]; then echo "$USERNAME available on this system" else echo "$USERNAME not found " fi
Numpad (13th April 2012)
Thank you!
hi,
to be precisetheses simple tests don't need if statements.Code:#!/bin/bash read -p "Please enter Username to check user exist or not:- " USERNAME grep -q $USERNAME /etc/passwd >/dev/null 2>&1 && echo "$USERNAME available on this system" || echo "$USERNAME not found "
beware, redirection has to be this, not rahul's; see bash man page about redirections.
Numpad (13th April 2012)
Hi Watael,
but why this also works "/etc/passwd 2>&1 >/dev/null"beware, redirection has to be this, not rahul's; see bash man page about redirections.
we knew it we can use "&& ||"Originally posted by Watael
don't need if statements.
but Numbad Question related to combine if and grep
thats the reason i post that code.
I understand. sometimes I do it too![]()
Hi Watael,
Thanks for correcting me
i am wrong, i checked all scripts under "/etc/init.d/" , in all scripts i found this code ">/dev/null 2>&1"
There are currently 1 users browsing this thread. (0 members and 1 guests)