I'm trying to do a basic if/else that checks to see if a cluster already exists before creating another of that name. This is the entire section;
cluster=$(aws eks list-clusters | jq -r ".clusters" | grep mycluster_test)
if [ $? -eq 0 ]; then
echo "this worked, the cluster is $cluster"
else
echo "no cluster by this name"
fi
There is no cluster with this name, and when I run the script it returns nothing. But I don't understand why it's not returning the else statement
I do have a cluster called 'mycluster_new' and when I grep for this, the first echo statement is returned, so can I please get help on why the else statement is failing. Thanks
try this
if your vairabe is string
if [[ $cluster == 1 ]]; then
if your variable is integer
if [[ $cluster -eq 1 ]]; then
Managed to resolve this by checking if the string was empty and ran a check that would continue regardless of if it was empty or not.
CLUSTER=my_eks_cluster
CHECK_NAME=$(aws eks list-clusters | jq -r ".clusters" | grep $CLUSTER || true)
then ran a check for this;
if [ "$CHECK_NAME" != "" ]; then
echo "There is already a cluster by this name; $CHECK_NAME. Cannot build another"
exit 1
else
echo "No cluster by this name $CLUSTER, will continue with terraform"
fi
if you really want to go ahead with your old way, you can always use '-z' to check if the string is null
if [ -z "$cluster" ]; then
echo "this worked, the cluster is $cluster"
else
echo "no cluster by this name"
fi
Related
I am writing a bash script that you can run on a server where mediawikis of games are deployed. I want to check if the wikis use SMTP. So a part of my script greps for the content in the config file that proves that they use SMTP.
The problem is, that I do that on multiple servers and I want to loop through multiple markets on a server. Not all servers share the same market names. In my script I have arrays that contain ALL market names. I want my script to account for the case that the grep cant find the file in which it is to look up if SMTP is used. How can I go about that?
I was thinking about a extra command to ask if the file exists before grepping. But that didn't work out as you can
for i in "${markets[#]}"; do
myPATH="/www/${game}_$i/${game}_$i/LocalSettings.php"
grepOut="grep -q 'wgSMTP = array(' "$myPATH""
if grep -q "wgSMTP = array(" "$myPATH"; then
echo -e "The Market ${BLUE}$i${NC} ${GREEN}uses${NC} SMTP."
else
if [[ "$grepOut" == *"No such file or directory"* ]]; then
if [[ "$market" == "all" ]]; then
echo -e "All markets:"
else
echo -e "The Market ${BLUE}$i doesn't${NC} exist on this server."
fi
else
echo -e "The Market ${BLUE}$i${NC} ${RED}doesn't${NC} use SMTP."
fi
fi
done
for i in "${markets[#]}"; do
path="/www/${game}_$i/${game}_$i/LocalSettings.php"
if ! [[ -f "$path" ]]; then
if [[ "$market" == "all" ]]; then
echo -e "All markets:"
else
echo -e "The Market ${BLUE}$i doesn't${NC} exist on this server."
fi
continue
fi
if grep -q 'wgSMTP = array(' "$path"; then
echo -e "The Market ${BLUE}$i${NC} ${GREEN}uses${NC} SMTP."
else
echo -e "The Market ${BLUE}$i${NC} ${RED}doesn't${NC} use SMTP."
fi
done
Not sure if $market should be $i (or vice versa).
i have a simple script that i want to display specific information from AWS using
AWS CLI.
for example:
get_cluster_name() {
EKS_NAME=$(aws eks describe-cluster --name ${CUSTOMER_NAME}) && \
echo $EKS_NAME | jq -r .cluster.name}
the output when the cluster exist is ok, i get the name of the cluster.
when the cluster does not exist, i get:
An error occurred (ResourceNotFoundException) when calling the DescribeCluster operation: No cluster found for name: example_cluster.
my goal is to get an empty output when a cluster is not found.
for that i wanted to use the return code in a condition or a string lookup in the output.
the issue is that the output is not stdout or stderr, therefor
i cant even direct it to /dev/null just to silence the error.
how can i make this code work properly?:
[[ $(get_cluster_name) =~ "ResourceNotFoundException" ]] && echo "EKS Cluster:....$(get_cluster_name)"
or
[[ $(get_cluster_name) ]] && echo "EKS Cluster:....$(get_cluster_name)"
Thank you.
Here's a consideration, and expansion on my comments. Again you're getting a stderr response when no cluster is found, so this makes this pretty straightforward.
Using >2 /dev/null to suppress that return message in stderr. Then using ret=$? to capture the return code.
get_cluster_name() {
EKS_NAME=$(aws eks describe-cluster --name ${CUSTOMER_NAME} 2> /dev/null);
ret=$?
if [ $ret -eq 0 ]; then
echo $EKS_NAME | jq -r .cluster.name
return 0
else
return $ret
fi
}
You can do the same thing now when you call the function as your error will propagate from aws command up the stack:
cluster=$(get_cluster_name)
ret=$?
if [ $ret -eq 0 ]; then
echo $cluster
else
echo "failed to find cluster. Error code: $ret"
fi
As an example.
I have a simple shell script which I want to set up as a periodic Jenkins job rather than a cronjob for visibility and usability for less experienced users.
Here is the script:
#!/bin/bash
outputfile=/opt/jhc/streaming/check_error_output.txt
if [ "grep -sq 'Unable' $outputfile" == "0" ]; then
echo -e "ERROR MESSAGE FOUND\n"
exit 1
else
echo -e "NO ERROR MESSAGES HAVE BEEN FOUND\n"
exit 0
fi
My script will always return "NO ERROR MESSAGES HAVE BEEN FOUND" regardless of whether or not 'Unable' is in $outputfile, what am I doing wrong?
I also need my Jenkins job to class this as a success if 'Unable' isn't found (e.g. If script returns "0" then pass, everything else is fail)
Execute the grep command and check the exit status instead:
#!/bin/bash
outputfile=/opt/jhc/streaming/check_error_output.txt
grep -sq 'Unable' $outputfile
if [ "$?" == "0" ]; then
echo -e "ERROR MESSAGE FOUND\n"
exit 1
else
echo -e "NO ERROR MESSAGES HAVE BEEN FOUND\n"
exit 0
fi
You are comparing two different strings. The outcome will always be false, i.e. the else part is taken.
Also, no need to explicitly query the status code. Do it like this:
if grep -sq 'Unable' $outputfile
then
....
else
....
fi
I am trying to check for duplicate records in my database using shell scripting.
For this, I have created a function named "check()" which echo's True or False and is stored in variable "result". But while evaluating using if statement it is always returning "True".
#redundancy check function
check() {
temp=$(grep -w -c "$1" database.dat)
echo $temp
if [ "$temp" != 0 ]
then
echo True
else
echo False
fi
}
insert() {
option="y"
while [ "$option" == "y" ]
do
echo "Rollno: \c"
read roll
result="$(check $roll)"
echo $result
if [ "$result" == "False" ]
then
echo Do something
else
echo "ERROR: Duplicate record found...\nEXITING...\n"
option="n"
fi
done
}
If you're using a shell that doesn't support the == extension to test, then your tests will always, unconditionally fail simply on account of invalid syntax. Use = for string comparisons to be portable to all POSIX-compliant implementations.
Moreover, there's no point to storing and then comparing the output from grep at all: Use the exit status of grep -q when your only goal is to check whether the number of matches is zero or more-than-zero; this allows grep to exit immediately when a match is seen, rather than needing to read the rest of the file.
# with -q, this emits no stdout, but exits w/ status 0 (matches exist) or 1 (otherwise)
check() { grep -q -w -e "$1" database.dat; }
insert() {
option=y
while [ "$option" = y ]; do
printf '%b\n' "Rollno: \c"
read -r roll
if check "$roll"; then
printf "ERROR: Duplicate record found...\nEXITING...\n"
option=n
else
echo "Check failed; do something"
fi
done
}
I'm writing a file transfer script and it gets pretty complex. So in the beginning when I generate my IP address to transfer from, I want to validate that I can indeed connect to it. The code in the area looks like this:
USER_ID=$1
if [[ $GROUP == "A" ]]; then
ADDRESS="${USER_ID}#morgan.company.gov"
elif [[ $GROUP == "B" ]]; then
ADDRESS="${USER_ID}#mendel.company.gov"
else
log_msg fatal "Couldn't resolve group $GROUP. Exiting"
exit 1;
fi
// HERE I want to test that $ADDRESS exists, and I can connect right now I
// have what is below. I just think there is a better way to do it
ssh -q $ADDRESS exit
if [ $? != 0 ]; then
log_msg fatal "Couldn't resolve host, do you have login privileges with $ADDRESS"
fi
... // lots of other things happen
scp $ADDRESS:$INCOMING_FILE $NEW_FILE
What I have works, but it doesn't seem like its an elegant solution. I'd prefer not to actually ssh and exit the server, just test the connection.
You can use this shell function that tests wether the host has the ssh port open or not:
#!/bin/bash
function isUp(){
local ip=$1
local sshport=22
if [[ $ip =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
if [[ $(nmap -P0 $ip -p$sshport | grep ^$sshport | cut -d' ' -f2) == "open" ]]; then
return 0
else
return 1
fi
fi
}
if isUp $1; then
ssh $1 uptime
else
echo "Host $1 is not available"
fi
or make use of this (new to me) bash functionality:
#!/bin/bash
function isUp(){
local ip=$1
if echo > /dev/tcp/$ip/22 >/dev/null 2>&1; then
return 0
else
return 1
fi
}
If you want to thoroughly check for the connection then you are better off analyzing the return codes from an scp connection. This will allow you to understand the reason why your connection failed and act in consequence (there may be various reasons at different levels, from a general lack of connectivity to issues with the keys for instance).
If you are just interested in a binary answer ("is my connection OK as it is?") then your code is fine, though I would directly use scp.
There is nothing wrong with your line:
ssh -q $ADDRESS exit
This is the best/fastest way to test a connection.