How to avoid the "temp files" in my script?

Hi ! :slight_smile:

I noticed that I create often of temporary files to keep character strings or other and I wish to avoid that if possible ? e.g :

#!/bin/bash
CONFIG_FILE="conf.cfg"
TEMP_HOSTNAME="temp_file1.txt"

for IP in `egrep -o '([0-9]{1,3}\.){3}[0-9]{1,3}' $CONFIG_FILE`
do
        ssh "$IP" 'hostname' > $TEMP_HOSTNAME
        REMOTE_HOSTNAME=$(cat "$TEMP_HOSTNAME")
        echo ""$IP" "$REMOTE_HOSTNAME"" >> temp_file2.txt
done

If you have any suggestions ? :b:

Maybe this...

TEMP_HOSTNAME=$(ssh "$IP" 'hostname')

For temp_file2 you may store the information into an associative array(bash version >= 4.0) like this:

# declaration (important! automatic created, undeclared arrays or numeric-indexed arrays)
declare -A temphosts

# assignment
temphosts[$IP]="$TEMP_HOSTNAME"

# access it again:
echo ${temphosts[$IP]}

# iterate over associative array
for idx in ${!temphosts[@]} ;do echo ${temphosts[$idx]};done
1 Like

Or, if you don't need the hostname further down the script and just want to collect the info in a file, try (untested):

for IP in $(egrep -o '([0-9]{1,3}\.){3}[0-9]{1,3}' $CONFIG_FILE)
  do    echo ""$IP" $(ssh "$IP" 'hostname')  >> temp_file2.txt
  done
1 Like