I have a simple shell script where I am doing a cURL and based on the response if empty or not wants to log a flag. I tried null check but it still goes to else part.
Script : test.sh
RESP=`curl -m 600 -X POST -H "Accept: application/json" ......` #curl response
#if [ -z "$RESP" ] && echo "Empty"
if [ ${#RESP[#]} -eq 0 ];
then
echo "APIName=Test1Api, TicketRaised=N"
else
echo "RESPONSE is NOT NULL"
echo -e "APIName=Test1Api, HTTP_STATUS=$HTTP_STATUS, totalTime=$TIME_TAKEN, Response=$RESP, TicketRaised=Y"
fi
Output > (even if Response ie "RESP" if empty it goes into else part)
RESPONSE is NOT NULL
APIName=Test1Api, HTTP_STATUS=[], totalTime=545, Response=[], TicketRaised=Y
I deduce from your answer that what you call an empty answer is the empty JASON string [].
So try:
RESP=`curl -m 600 -X POST -H "Accept: application/json" ......` #curl response
if [ $RESP = "[]" ]
then
echo "APIName=Test1Api, TicketRaised=N"
else
echo "RESPONSE is NOT NULL"
echo -e "APIName=Test1Api, HTTP_STATUS=$HTTP_STATUS, totalTime=$TIME_TAKEN, Response=$RESP, TicketRaised=Y"
fi
Be sure that there is no newline char after []. Otherwise, you will have to adapt the code.
Related
I have created a simple bash script that help you to mute alert within a few second without going into the console.
prerequisite:
jq needs to be installed on local
you should know some portion of your detector.
ex- If I want to mute alert with for detector name "prod-test memory utilization" then while mute alert via script I will simply type prod-test
Token should be created on signalfx so that we can authenticate from local
Ref: https://docs.splunk.com/Observability/alerts-detectors-notifications/mute-notifications.html#nav-Mute-alert-notifications
#!/bin/bash
echo -e "Please enter SFx token to authenticate\n"
read TOKEN
echo -e " \n"
echo -e "Please copy-paste any one muting option from below. \n a) Mute_Indefinitely \n b) Mute_By_Duration \n"
read MUTE_OPTION
echo -e " \n"
## this is comman name from detector in my case it is prod-test and prod-test2"
echo -e "Please copy-paste the server name which you wish to mute.
1. prod-test
2. prod-test2\n"
read SERVER_NAME
echo "Fatching detectors ids, Please wait for few seconds..."
DETECTOR_ID=$(curl -s -X GET "https://<your sfx url>/v2/detector?limit=2000" -H "Content-Type: application/json" -H "X-SF-TOKEN: "$TOKEN"" | jq -r '.results[] | select(.name | contains("'"$SERVER_NAME"'")).id')
############### MUTE BY DURATION FUNCTION ###############
mute_by_duration () {
START_TIME=`date +%s%N | cut -b1-13`
END_TIME=`date -d "+$min minutes" +%s%N | cut -b1-13`
curl -X "POST" "https://<your sfx url>/v2/alertmuting" \
-H 'X-SF-TOKEN: '$TOKEN'' \
-H 'Content-Type: application/json' \
-d $'{
"startTime": "'"$START_TIME"'",
"stopTime": "'"$END_TIME"'",
"filters": [
{
"property": "sf_detectorId",
"propertyValue": "'"$i"'"
}
]
}'
if [ $? -eq 0 ]; then
echo -e "\nDetector has been muted\n"
fi
}
############# MUTE ALERT INDEFINITELY ################
mute_indefinitely () {
curl -X "POST" "https://<your sfx url>/v2/alertmuting" \
-H 'X-SF-TOKEN: '$TOKEN'' \
-H 'Content-Type: application/json' \
-d $'{
"startTime": "",
"stopTime": "",
"filters": [
{
"property": "sf_detectorId",
"propertyValue": "'"$i"'"
}
]
}'
if [ $? -eq 0 ]; then
echo -e "\nDetector has been muted\n"
fi
}
#################### MUTING OPTION ###############
muting_rule() {
case "$MUTE_OPTION" in
"Mute_Indefinitely") echo -e "\n***** You have selected Mute_Indefinitely option, don't forget to unmute later *****\n";
for i in $DETECTOR_ID; do mute_indefinitely; done
;;
"Mute_By_Duration") echo -e "\n***** You have selected Mute_By_Duration option, This Alert will auto unmute after $min minutes *****\n";
for i in $DETECTOR_ID; do mute_by_duration; done
;;
*) echo "Please select correct option"
esac
}
############# SELECTION BASED ON MUTING OPTION #######################
if [ "$MUTE_OPTION" == Mute_By_Duration ]; then
echo -e "How much minutes you want to mute alert from current time? \n Example: Type "30" to mute for 30 mins \n"
read min
muting_rule
elif [ "$MUTE_OPTION" == Mute_Indefinitely ]; then
muting_rule
else
echo "Invalid Option"
fi
I'm building a bash script to send an email based off the last command. I seem to be having difficulties. Outside of a script the command works fine but when putting it in script it doesn't give the desired outcome.
Here is snippet of script:
grep -vFxf /path/to/first/file /path/to/second/file > /path/to/output/file.txt
if [ -s file.txt ] || echo "file is empty";
then
swaks -t "1#email.com" -f "norply#email.com" --header "Subject: sample" --body "Empty"
else
swaks -t "1#email.com" -f "norply#email.com" --header "subject: sample" --body "Not Empty"
fi
I ran the commands outside of script and I can see that there is data but when I add the commands within script I get the empty output. Please advise . Thank you in advance .
Your condition will always be true, because if [ -s file.txt ] fails, the exit status of the ||-list is the exit status of echo, which is almost guaranteed to be 0. You want to move the echo out of the condition and into the body of the if statement. (And to simplify further, just set the body to a variable and call swaks after the if completes.
if [ -s file.txt ];
then
body="Not Empty"
else
echo "file is empty"
body="Empty"
fi
swaks -t "1#email.com" -f "norply#email.com" --header "subject: sample" --body "$body"
If the only reason you create file.txt is to check if it is empty or not, you can just put the grep command directly in the if condition:
if grep -vFxfq /atph/to/first/file /path/to/second/file; then
body="Not Empty"
else
echo "No output"
body="Empty"
fi
swaks -t "1#email.com" -f "norply#email.com" --header "subject: sample" --body "$body"
I have a shell Unix running every hour (crontab on CentOS 7).
Inside that shell, a loop read and proceed treatment for all new files find in a defined folder.
At the end of each files's treatment a CURL command is send with some parameters, for example :
curl https://aaaaaa.com/website -d param1=value1 -d param2=value2 ....
Each time the shell is run by crontab, the 1st CURL is correctly converted to a true URL and received by Apache/Tomcat, but all the others are bad. In fact the 2nd and the following CURLs seem not converted in the correct format like
https://aaaaaa.com/website?param1=value1¶m2=value2
but they are sent like
https://aaaaaa.com/website -d param1=value1 -d param2=value2
So the website is unable to treat the parameters properly.
Why the 1st command is correctly converted to a correct URL format and not the following ?
EDIT - EDIT
The part of shell :
#!/bin/bash
...
#======================================================
# FUNCTIONS
#======================================================
UpdateStatus () {
CMD_CURL="${URL_WEBSITE} -d client=CLIENT -d site=TEST -d produit=MEDIASFILES -d action=update"
CMD_CURL="${CMD_CURL} -d codecmd=UPDATE_MEDIA_STATUS"
CMD_CURL="${CMD_CURL} -d idmedia=$4"
CMD_CURL="${CMD_CURL} -d idbatch=$3"
CMD_CURL="${CMD_CURL} -d statusmedia=$2"
if [[ ! -z "$5" ]]; then
CMD_CURL="${CMD_CURL} -d filename=$5"
fi
echo " ${CMD_CURL}" >> $1
CURL_RESULT=`curl -k ${CMD_CURL}`
CURL_RESULT=`echo ${CURL_RESULT} | tr -d ' '`
echo " Result CURL = ${CURL_RESULT}" >> $1
if [ "${CURL_RESULT}" = "OK" ]; then
return 0
fi
return 1
}
#======================================================
# MAIN PROGRAM
#======================================================
echo "----- Batch in progress : `date '+%d/%m/%y - %H:%M:%S'` -----"
for file in $( ls ${DIR_FACTORY_BATCHFILES}/*.batch )
do
...
old_IFS=$IFS
while IFS=';' read <&3 F_STATUS F_FILEIN F_TYPE F_CODE F_ID F_IDPARENT F_TAGID3 F_PROF F_YEARMEDIA F_DATECOURS F_TIMEBEGINCOURS F_LANG || [[ -n "$F_STATUS $F_FILEIN $F_TYPE $F_CODE $F_ID $F_IDPARENT $F_TAGID3 $F_PROF $F_YEARMEDIA $F_DATECOURS $F_TIMEBEGINCOURS $F_LANG" && $F_STATUS ]];
do
...
UpdateStatus ${LOG_FILENAME} ${STATUS_ERROR} ${F_ID} ${F_IDPARENT}
...
done 3< $file
IFS=$Old_IFS
...
done
You need to provide the "-d" flags and values before the URL so:
curl -d param1=value1 -d param2=value2 https://aaaaaa.com/website
Moreover, this command is going to send the parameters/values as POST parameters, not query parameters. You can use the "-G" flag, possibly combined with "--url-encode" to send as query parameters, see:
https://unix.stackexchange.com/questions/86729/any-way-to-encode-the-url-in-curl-command
I have a webservice provided at http://localhost/test/testweb
I want to write a script to check if webservice is up with curl
If there a curl parameter given, returns 200 OK ok true false so that I can use it is if-else block in linux script
curl -sL -w "%{http_code}\\n" "http://www.google.com/" -o /dev/null
-s = Silent cURL's output
-L = Follow redirects
-w = Custom output format
-o = Redirects the HTML output to /dev/null
Example:
[~]$ curl -sL -w "%{http_code}\\n" "http://www.google.com/" -o /dev/null
200
I would probably remove the \\n if I were to capture the output.
I use:
curl -f -s -I "http://example.com" &>/dev/null && echo OK || echo FAIL
-f --fail Fail silently (no output at all) on HTTP errors
-s --silent Silent mode
-I --head Show document info only
Note:
depending on needs you can also remove the "-I" because in some cases you need to do a GET and not a HEAD
Same as #burhan-khalid, but added --connect-timeout 3 and --max-time 5.
test_command='curl -sL \
-w "%{http_code}\\n" \
"http://www.google.com:8080/" \
-o /dev/null \
--connect-timeout 3 \
--max-time 5'
if [ $(test_command) == "200" ] ;
then
echo "OK" ;
else
echo "KO" ;
fi
That will check the headers via wget 2>&1pipes the stderr to stdout
grep filters
-O /dev/null just throws the content of the page
if [ "\`wget http://example.org/ -O /dev/null -S --quiet 2>&1 | grep '200 OK'\`" != "" ];
then
echo Hello;
fi;
I know not curl, but still a solution
I needed a better answer to this, so I wrote the script below.
The fakePhrase is used to detect ISP "Search Assist" adware HTTP resposnes.
#!/bin/bash
fakePhrase="verizon"
siteList=(
'http://google.com'
'https://google.com'
'http://wikipedia.org'
'https://wikipedia.org'
'http://cantgettherefromhere'
'http://searchassist.verizon.com'
)
exitStatus=0
function isUp {
http=`curl -sL -w "%{http_code}" "$1" -o temp_isUp`
fakeResponse=`cat temp_isUp | grep $fakePhrase`
if [ -n "$fakeResponse" ]; then
http=$fakePhrase
fi
case $http in
[2]*)
;;
[3]*)
echo 'Redirect'
;;
[4]*)
exitStatus=4
echo "$1 is DENIED with ${http}"
;;
[5]*)
exitStatus=5
echo "$1 is ERROR with ${http}"
;;
*)
exitStatus=6
echo "$1 is NO RESPONSE with ${http}"
;;
esac
}
for var in "${siteList[#]}"
do
isUp $var
done
if [ "$exitStatus" -eq "0" ]; then
echo 'All up'
fi
rm temp_isUp
exit $exitStatus
Use this:
curl -o $CURL_OUTPUT -s -w %{http_code}\\n%{time_total}\\n $URL > $TMP_FILE 2>&1
cat $TMP_FILE
I have this CGI script, but how do I start a download in the browser?
#!/bin/bash
echo "Content-Type: text/plain"
echo
CUR=$(ls -t /var/www/html/certs/*$AUTHENTICATE_UID* | head -1)
if [ "$CUR" != "" ]; then
# start download in the browser
fi
Typically, you would emit the Content-Disposition header:
echo "Content-Type: text/plain"
CUR=$(ls -t /var/www/html/certs/*$AUTHENTICATE_UID* | head -1)
if [ "$CUR" != "" ]; then
echo 'Content-Disposition: attachment; filename="yourFile.txt"'
fi
echo # End of headers.