pirulo
pirulo

Reputation: 385

write user input to a file

I'm trying to get information saved to a file, but I'm only getting the last line.

Is my method for saving the output, > $fqdn_alias.decom, is wrong?

qdn_alias=$(hostname --alias)
blade_sn=$(dmidecode -t system | grep "Serial Number")
blade_slot=$(dmidecode | grep "Location In")
wwn_ports=/tmp/wwn.txt
port_name=$(cat /sys/class/fc_host/host[0-9]/port_name)
# store wwn ports
echo "$port_name" > $wwn_ports
# output
echo "Server Alias:" $fqdn_alias > $fqdn_alias.decom
echo "" > $fqdn_alias.decom
echo "WWN" > $fqdn_alias.decom
sed 's/\(..\)/\1:/g;s/:$//' $wwn_ports > $fqdn_lias.decom
echo "" > $fqdn_alias.decom
echo "$blade_slot" > $fqdn_alias.decom
echo "$blade_sn" > $fqdn_alias.decom

Upvotes: 0

Views: 102

Answers (2)

Tom Fenech
Tom Fenech

Reputation: 74685

Every time you use >, it truncates the file before writing to it. So if you do this many times in a row, you're repeatedly emptying the file.

The best solution is to only open the file for writing once.

One option would be to group your commands using a block, like this:

{    
    echo "Server Alias: $fqdn_alias"
    echo ""
    echo "WWN"
    sed 's/\(..\)/\1:/g;s/:$//' "$wwn_ports"
    echo ""
    echo "$blade_slot"
    echo "$blade_sn"    
} > "$fqdn_alias.decom"

Using this approach, the file is only opened for writing once. As a bonus, I've added some healthy quotes around your variables, which is always a good idea.

Alternatively, you could go with a heredoc:

cat <<EOF >"$fqdn_alias.decom"
Server Alias: $fqdn_alias

WWW
$(sed 's/\(..\)/\1:/g;s/:$//' "$wwn_ports")

$blade_slot
$blade_sn
EOF

The lines up to EOF are redirected to the file. This option is nicer in my opinion, as it avoids so many calls to echo and allows you to use newlines. A command substitution is used to add the output of the sed command.

Upvotes: 2

Eric Renouf
Eric Renouf

Reputation: 14510

Everytime you redirect with > it will overwrite the existing file. If you want to append to the file use >> so your lines should be, say

sed 's/\(..\)/\1:/g;s/:$//' $wwn_ports >> $fqdn_lias.decom

Or you could do them all in a block/subshell if you don't worry about the overhead and redirect the output from that like

( echo "Server Alias:" $fqdn_alias 
echo ""
echo "WWN" 
sed 's/\(..\)/\1:/g;s/:$//' $wwn_ports
echo "" 
echo "$blade_slot" 
echo "$blade_sn" ) > $fqdn_alias.decom

Upvotes: 1

Related Questions