Setting a variable inside a conditional - bash

Is it possible to set a variable from the output of a command inside of a conditional where the conditional is false if nothing gets assigned to the variable.
If I set the variable to a grep with no return and then test:
test=$(echo hello | grep 'helo')
if [[ ! -z $test ]]; then
echo "is set"
else
echo "not set"
fi
Output: not set (this is expected)
But I'm trying to put it all into one statement like this:
test=
if [[ ! -z test=$(echo hello | grep 'helo') ]]; then
echo "is set"
else
echo "not set"
fi
output: "is set" (expected not set)

grep returns success if there is a match, so you can just do:
if test=$(echo hello | grep 'helo')
then
echo "Match: $test"
else
echo "No match"
fi
If you're running something that doesn't differentiate by exit code, you can assign and check in two statements on the same line:
if var=$(cat) && [[ -n $var ]]
then
echo "You successfully piped in some data."
else
echo "Error or eof without data on stdin."
fi
(or ; instead of && if you want to inspect the result even when the command reports failure)

Bit of a hack, using the shell's parameter expansion alternate value syntax, echo -e and some backspaces:
test=$(echo hello | grep 'helo'); echo -e not${test:+\\b\\b\\bis} set
Which outputs is set or not set depending on what grep finds.

Related

Perform action if nothing is returned

I'm trying to echo "It was not found" if the netstat returns no result. But, if it does return a result, then to display the netstat results.
I'm trying to google for what I'm using and can't find much about it.
#!/bin/bash
echo "Which process would you like to run netstat against?"
read psname
echo "Looking for '$psname'"
sleep 2
command=$(netstat -tulpn | grep -e $psname)
[[ ! -z $command ]]
It's to do with the [[ ! -z $command ]]
[[ ! -z $command ]] doesn't 'show' you any output.
Use a if/else setup to show the result;
if [[ ! -z $command ]]; then
echo "$psname was found!"
else
echo "No process named '${psname}' found!"
fi
Or a shorthand variant;
[[ ! -z $command ]] && echo "$psname was found!" || echo "No process named '${psname}' found!"
Note if the user input may contain a space, it's saver to use "" around the grep string;
command=$(netstat -tulpn | grep -e "$psname")
When to wrap quotes around a shell variable?
Do not intercept the output directly. You can instead do something like:
if ! netstat -tulpn | grep -e "$psname"; then
echo "not found" >&2
fi
If grep matches any output, it will print it to stdout. If it mathches nothing, it returns non-zero and the shell will write a message to stderr.

How to use if inside a command in bash script?

I am writing a script in bash, and I have a problem with it:
select opt in "${options[#]}"
do
case $opt in
"1) Check Cassandra Status.")
ssh skyusr#"$IP" "export JAVA_HOME=/opt/mesosphere && /var/lib/mesos/slave/slaves/*/frameworks/*/executors/*/runs/latest/apache-cassandra-3.0.10/bin/nodetool -p 7199 status" | sed -n '6,10p' | awk '{print $1,$2}' | DN="$(grep DN)" | [[if [[!DN]]; echo "All Good" else "Node(s) "$DN" is Down" ;fi]]
;;
"2) Run Repair on all nodes.")
echo "you chose choice 2"
;;
"3) Run Refresh on specific keyspace/Table.")
echo "you chose choice 3"
;;
"4) Optional")
echo "This option disabled"
;;
"Quit")
break
;;
*) echo invalid option;;
esac
done
It gives me
error:line 16: [[if: command not found
All was working until I added this if command, I need to echo a message if $DN is empty else echo another message .
You seem to be confused about some of Bash's basic concepts like pipelines (|) versus compound commands (if and [[). For example awk '{print $1,$2}' | DN="$(grep DN)" does probably not do what you expect:
$ echo $'a\nb'
a
b
$ echo $'a\nb' | B=$(grep a)
$ echo $B
Note how the variable B is not set to "a".
Furthermore your syntax DN="$(grep DN)" | [[if [[!DN]]; echo "All Good" is complete nonsense. You best start by reading some introduction. Then you can continue along the lines of:
A=$(....)
[[ -z $A ]] && echo "A is empty"
# or
if [[ -z $A ]] then echo "A is empty"; else echo "A is not empty"; fi
Change your if condition like below. Your if condition syntax is not correct and then part is also missing. I have just corrected the if condition rest you need to check again.
if [[ DN == "" ]]; then echo "All Good" else echo "Node(s) $DN is Down" ; fi

While file doesn't contain string BASH

I am making a script for my school, and I was wondering how I could check a file, and if the string isn't in the file, do a code, but if it is, continue, like this:
while [ -z $(cat File.txt | grep "string" ) ] #Checking if file doesn't contain string
do
echo "No matching string!, trying again" #If it doesn't, run this code
done
echo "String matched!" #If it does, run this code
You can do something like:
$ if grep "string" file;then echo "found";else echo "not found"
To do a loop :
$ while ! grep "no" file;do echo "not found";sleep 2;done
$ echo "found"
But be carefull not to enter an infinite loop. string or file must be changed otherwise the loop has no meaning.
Above if/while works based on the return status of the command and not on the result.
if grep finds string in file will return 0 = success = true
if grep does not find string will return 1 = not success = false
By using ! we revert the "false" to "true" to keep the loop running since while loops on something as soon as it is true.
A more conventional while loop would be similar to your code but without the useless use of cat and the extra pipe:
$ while [ -z $(grep "no" a.txt) ];do echo "not found";sleep 2;done
$ echo "found"
A simple if statement to test if a 'string' is not in file.txt:
#!/bin/bash
if ! grep -q string file.txt; then
echo "string not found in file!"
else
echo "string found in file!"
fi
The -q option (--quiet, --silent) ensures output is not written to standard output.
A simple while loop to test is a 'string' is not in file.txt:
#!/bin/bash
while ! grep -q string file.txt; do
echo "string not found in file!"
done
echo "string found in file!"
Note: be aware of the possibility that the while loop may cause a infinite loop!
Another simple way is to just do the following:
[[ -z $(grep string file.file) ]] && echo "not found" || echo "found"
&& means AND - or execute the following command if the previous is true
|| means OR - or execute if the previous is false
[[ -z $(expansion) ]] means return true if the expansion output is null
This line is much like a double negative, basically:
"return true if the string is not found in file.file; then echo not found if true, or found if false"
Example:
bashPrompt:$ [[ -z $(grep stackOverflow scsi_reservations.sh) ]] && echo "not found" || echo "found"
not found
bashPrompt:$ [[ -z $(grep reservations scsi_reservations.sh) ]] && echo "not found" || echo "found"
found

Bash string comparison of two identical strings false?

Hello I have the following script:
#! /bin/bash
Output=$(defaults read com.apple.systemuiserver menuExtras | grep Bluetooth.menu)
Check="\"/System/Library/CoreServices/Menu Extras/Bluetooth.menu\","
echo $Output
echo $Check
if [ "$Output" = "$Check" ]
then
echo "OK"
else
echo "FALSE"
echo "Security Compliance Setting 'Show Bluetooth Status in Menu Bar(2.1.3)' has been changed!" | logger
fi
When you run it, both variables have the exact same output however the check always says it is FALSE
here is the out put from my terminal:
"/System/Library/CoreServices/Menu Extras/Bluetooth.menu",
"/System/Library/CoreServices/Menu Extras/Bluetooth.menu",
FALSE
Any idea why it is not detecting that they are the same?
As everyone in the comments suspected, the problem is whitespace in $Output (which echo $Output removes); specifically, 4 leading spaces (note that in the following, "$ " is my shell prompt):
$ defaults read com.apple.systemuiserver menuExtras | grep Bluetooth.menu
"/System/Library/CoreServices/Menu Extras/Bluetooth.menu",
$ Output=$(defaults read com.apple.systemuiserver menuExtras | grep Bluetooth.menu)
$ echo $Output
"/System/Library/CoreServices/Menu Extras/Bluetooth.menu",
$ echo "[$Output]"
[ "/System/Library/CoreServices/Menu Extras/Bluetooth.menu",]
$ Check=" \"/System/Library/CoreServices/Menu Extras/Bluetooth.menu\","
$ if [ "$Output" = "$Check" ]; then echo "OK"; else echo "FALSE"; fi
OK
Note that since the number of spaces might not always be the same, it might be safer to use bash's wildcard matching capability within a [[ ]] conditional expression (this will not work with [ ]):
$ Check="\"/System/Library/CoreServices/Menu Extras/Bluetooth.menu\","
$ if [[ "$Output" = *"$Check" ]]; then echo "OK"; else echo "FALSE"; fi
OK
You could also skip the string comparison entirely, and just use the fact that grep returns a success status only if it finds a match:
#!/bin/bash
if defaults read com.apple.systemuiserver menuExtras | grep -q "/System/Library/CoreServices/Menu Extras/Bluetooth.menu"; then
echo "OK"
else
echo "FALSE"
echo "Security Compliance Setting 'Show Bluetooth Status in Menu Bar(2.1.3)' has been changed!" | logger
fi

How to check if a file contains a specific string using Bash

I want to check if a file contains a specific string or not in bash. I used this script, but it doesn't work:
if [[ 'grep 'SomeString' $File' ]];then
# Some Actions
fi
What's wrong in my code?
if grep -q SomeString "$File"; then
Some Actions # SomeString was found
fi
You don't need [[ ]] here. Just run the command directly. Add -q option when you don't need the string displayed when it was found.
The grep command returns 0 or 1 in the exit code depending on
the result of search. 0 if something was found; 1 otherwise.
$ echo hello | grep hi ; echo $?
1
$ echo hello | grep he ; echo $?
hello
0
$ echo hello | grep -q he ; echo $?
0
You can specify commands as an condition of if. If the command returns 0 in its exitcode that means that the condition is true; otherwise false.
$ if /bin/true; then echo that is true; fi
that is true
$ if /bin/false; then echo that is true; fi
$
As you can see you run here the programs directly. No additional [] or [[]].
In case if you want to check whether file does not contain a specific string, you can do it as follows.
if ! grep -q SomeString "$File"; then
Some Actions # SomeString was not found
fi
In addition to other answers, which told you how to do what you wanted, I try to explain what was wrong (which is what you wanted.
In Bash, if is to be followed with a command. If the exit code of this command is equal to 0, then the then part is executed, else the else part if any is executed.
You can do that with any command as explained in other answers: if /bin/true; then ...; fi
[[ is an internal bash command dedicated to some tests, like file existence, variable comparisons. Similarly [ is an external command (it is located typically in /usr/bin/[) that performs roughly the same tests but needs ] as a final argument, which is why ] must be padded with a space on the left, which is not the case with ]].
Here you needn't [[ nor [.
Another thing is the way you quote things. In bash, there is only one case where pairs of quotes do nest, it is "$(command "argument")". But in 'grep 'SomeString' $File' you have only one word, because 'grep ' is a quoted unit, which is concatenated with SomeString and then again concatenated with ' $File'. The variable $File is not even replaced with its value because of the use of single quotes. The proper way to do that is grep 'SomeString' "$File".
Shortest (correct) version:
grep -q "something" file; [ $? -eq 0 ] && echo "yes" || echo "no"
can be also written as
grep -q "something" file; test $? -eq 0 && echo "yes" || echo "no"
but you dont need to explicitly test it in this case, so the same with:
grep -q "something" file && echo "yes" || echo "no"
##To check for a particular string in a file
cd PATH_TO_YOUR_DIRECTORY #Changing directory to your working directory
File=YOUR_FILENAME
if grep -q STRING_YOU_ARE_CHECKING_FOR "$File"; ##note the space after the string you are searching for
then
echo "Hooray!!It's available"
else
echo "Oops!!Not available"
fi
grep -q [PATTERN] [FILE] && echo $?
The exit status is 0 (true) if the pattern was found; otherwise blankstring.
if grep -q [string] [filename]
then
[whatever action]
fi
Example
if grep -q 'my cat is in a tree' /tmp/cat.txt
then
mkdir cat
fi
In case you want to checkif the string matches the whole line and if it is a fixed string, You can do it this way
grep -Fxq [String] [filePath]
example
searchString="Hello World"
file="./test.log"
if grep -Fxq "$searchString" $file
then
echo "String found in $file"
else
echo "String not found in $file"
fi
From the man file:
-F, --fixed-strings
Interpret PATTERN as a list of fixed strings, separated by newlines, any of
which is to be matched.
(-F is specified by POSIX.)
-x, --line-regexp
Select only those matches that exactly match the whole line. (-x is specified by
POSIX.)
-q, --quiet, --silent
Quiet; do not write anything to standard output. Exit immediately with zero
status if any match is
found, even if an error was detected. Also see the -s or --no-messages
option. (-q is specified by
POSIX.)
Try this:
if [[ $(grep "SomeString" $File) ]] ; then
echo "Found"
else
echo "Not Found"
fi
I done this, seems to work fine
if grep $SearchTerm $FileToSearch; then
echo "$SearchTerm found OK"
else
echo "$SearchTerm not found"
fi
grep -q "something" file
[[ !? -eq 0 ]] && echo "yes" || echo "no"

Resources