0
#!/bin/bash

ARRAY="185.18.207.66 31.18.212.113"

result=""

for i in $ARRAY
do  
    result=$(printf '%s %s' "$result" "$i" "checked")
done

paste <(printf "%s\n" $result)

I am trying to print IP addresses but with appending "checked" phrase for each IP address.

But I can not print a space between IP and "checked" phrase

Above code prints:

185.18.207.66checked
31.18.212.113checked

How can I make it to print like below?

185.18.207.66 checked
31.18.212.113 checked 
0

1 Answer 1

2

There are many things to improve with your script before making it done right:

  • Missing double quote
  • Spawning unnecessary external commands.

Just using an array instead:

#!/bin/bash

ARRAY=(185.18.207.66 31.18.212.113)
printf '%s checked\n' "${ARRAY[@]}"

or using "$@" to make it POSIXly:

#!/bin/sh

set -- 185.18.207.66 31.18.212.113

printf '%s checked\n' "$@"
6
  • Thanks. Actually, I need to read access_log and iterate over the IPs. So I just used a simple "for" loop as an example. Would you mind showing me the way I provided please? I know your way looks better but my current script requires this way.
    – NecNecco
    Commented Apr 5, 2016 at 9:46
  • 1
    @NecNecco: You can save to an array variable for each IP then print them all after finish reading the log. And why don't you just print it out immediately when you got and IP?
    – cuonglm
    Commented Apr 5, 2016 at 9:57
  • I use sort | uniq -c | sort -nr for access_log. So I gather the IP list, than checking if the IP is blocklisted in IPtables. If it is already banned, I removed it from the list. After iterating all, I print out only the IPs that are not banned.
    – NecNecco
    Commented Apr 5, 2016 at 10:19
  • 1
    So just do set -f; ARRAY=( $(<your_command_here) ); set +f then use for ip in "${ARRAY[@]}".
    – cuonglm
    Commented Apr 5, 2016 at 10:44
  • 1
    @NecNecco: printf is a bash builtin, so you should you it when possible.
    – cuonglm
    Commented Apr 6, 2016 at 8:56

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.