BASH shell script echo to output on a single line

I have a simple BASH script shell that checks the HTTP response code of the curl command. The logic is fine, but I was stuck on "just," printing out the "exit."

I am using GNU bash, version 3.2.25 (1) -release (x86_64-redhat-linux-gnu)

I would like to display a tabbed URL - then the answer is 404 | 200 | 501 | 502. For example:

http://www.google.co.uk<tab>200 

I also get a weird error when the "http" part of the URL is rewritten using 200 | 404 | 501 | 502. Is there a basic script (function) of the BASH shell that I do not use?

thanks

Miles.

 #!/bin/bash NAMES=`cat $1` for i in $NAMES do URL=$i statuscode=`curl -s -I -L $i |grep 'HTTP' | awk '{print $2}'` case $statuscode in 200) echo -ne $URL\t$statuscode;; 301) echo -ne "\t $statuscode";; 302) echo -ne "\t $statuscode";; 404) echo -ne "\t $statuscode";; esac done 
+4
source share
3 answers

In this answer you can use the code

response=$(curl --write-out %{http_code} --silent --output /dev/null servername)


Substituted in your loop, it will be

 #!/bin/bash NAMES=`cat $1` for i in $NAMES do URL=$i statuscode=$(curl --write-out %{http_code} --silent --output /dev/null $i) case $statuscode in 200) echo -e "$URL\t$statuscode" ;; 301) echo -e "$URL\t$statuscode" ;; 302) echo -e "$URL\t$statuscode" ;; 404) echo -e "$URL\t$statuscode" ;; * ) ;; esac done 

I cleared the echo expressions, so there is a new line for each URL.

+2
source

try

  200) echo -ne "$URL\t$statuscode" ;; 
+1
source

I am doing a shot here, but I think it bothers you that curl sometimes returns more than one header information (hence more than one status code) when the initial request is redirected.

For instance:

 [ me@hoe ]$ curl -sIL www.google.com | awk '/HTTP/{print $2}' 302 200 

When you print this in a loop, it looks like the second status code has become part of the following URL.

If this is really your problem, then there are several ways to solve this problem, depending on what you are trying to achieve.

  • If you do not want to follow the redirects, just leave the -L option in curl

     statuscode=$(curl -sI $i | awk '/HTTP/{print $2}') 
  • To take only the last status code, simply run the entire command to tail -n1 to take only the last.

     statuscode=$(curl -sI $i | awk '/HTTP/{print $2}' | tail -n1) 
  • To show all codes in order, replace all lines with spaces

     statuscode=$(curl -sI $i | awk '/HTTP/{print $2}' | tr "\n" " ") 

For example, using the third scenario:

 [ me@home ]$ cat script.sh #!/bin/bash for URL in www.stackoverflow.com stackoverflow.com stackoverflow.com/xxx do statuscode=$(curl -siL $i | awk '/^HTTP/{print $2}' | tr '\n' ' ') echo -e "${URL}\t${statuscode}" done [ me@home ]$ ./script.sh www.stackoverflow.com 301 200 stackoverflow.com 200 stackoverflow.com/xxx 404 
0
source

Source: https://habr.com/ru/post/1382511/


All Articles