I would like to have the echo
command executed when cat /etc/passwd | grep "sysa"
is not true.
What am I doing wrong?
if ! [ $(cat /etc/passwd | grep "sysa") ]; then echo "ERROR - The user sysa could not be looked up" exit 2 fi
What is the Bash if Statement? Bash scripts help automate tasks on your machine. The if elif else statement in bash scripts allows creating conditional cases and responses to specific code results. The if conditional helps automate a decision-making process during a program.
To find out if a bash variable is empty: Return true if a bash variable is unset or set to the empty string: if [ -z "$var" ]; Another option: [ -z "$var" ] && echo "Empty" Determine if a bash variable is empty: [[ ! -z "$var" ]] && echo "Not empty" || echo "Empty"
In order to check if a file does not exist using Bash, you have to use the “!” symbol followed by the “-f” option and the file that you want to check. Similarly, you can use shorter forms if you want to quickly check if a file does not exist directly in your terminal.
A variable in bash is created by assigning a value to its reference. Although the built-in declare statement does not need to be used to explicitly declare a variable in bash, the command is often employed for more advanced variable management tasks.
try
if ! grep -q sysa /etc/passwd ; then
grep
returns true
if it finds the search target, and false
if it doesn't.
So NOT false
== true
.
if
evaluation in shells are designed to be very flexible, and many times doesn't require chains of commands (as you have written).
Also, looking at your code as is, your use of the $( ... )
form of cmd-substitution is to be commended, but think about what is coming out of the process. Try echo $(cat /etc/passwd | grep "sysa")
to see what I mean. You can take that further by using the -c
(count) option to grep and then do if ! [ $(grep -c "sysa" /etc/passwd) -eq 0 ] ; then
which works but is rather old school.
BUT, you could use the newest shell features (arithmetic evaluation) like
if ! (( $(grep -c "sysa" /etc/passwd) == 0 )) ; then ...`
which also gives you the benefit of using the c-lang based comparison operators, ==,<,>,>=,<=,%
and maybe a few others.
In this case, per a comment by Orwellophile, the arithmetic evaluation can be pared down even further, like
if ! (( $(grep -c "sysa" /etc/passwd) )) ; then ....
OR
if (( ! $(grep -c "sysa" /etc/passwd) )) ; then ....
Finally, there is an award called the Useless Use of Cat (UUOC)
. :-) Some people will jump up and down and cry gothca! I'll just say that grep
can take a file name on its cmd-line, so why invoke extra processes and pipe constructions when you don't have to? ;-)
I hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With