user2030520
user2030520

Reputation: 13

Concatenating variables in bash(debian)

I have seen a number of ways how concatenation of variables are supposed to work but they are not working how I would expect and not sure why...
I am reading a txt file into an array each row is a domain name I want to do an zone transfer output that to a file with the filename domain.zone simple right....

ok well here is the script I have commected out the actual dig part

#!/bin/bash
filecontent=($(cat goodFvzones.txt))
for t in "${filecontent[@]}"
do
n=".zone"
x=$t$n
echo "$x"
#dig @dnsserver -t axfr $t > $x
done

When I run the above script if the domainname it was working on was domain.com what I get as output is: .zonen.com

Expected output would be domain.com.zone
The content of variable n (5 charaters) is overwriting the first 5 charaters of variable t Can someone explain what I am doing wrong I think it must have something to do with the period but have not been able to figure it out.

Upvotes: 1

Views: 983

Answers (2)

William
William

Reputation: 4935

You can add a carriage return (\r) to IFS to make it just another whitespace character for argument parsing purposes:

IFS=$(printf "$IFS\r")
filecontent=($(cat goodFvzones.txt))
for t in "${filecontent[@]}"
do
  n=".zone"
  x=$t$n
  echo "$x"
  #dig @dnsserver -t axfr $t > $x
done

Upvotes: 0

Anton Kovalenko
Anton Kovalenko

Reputation: 21507

When you notice a shorter string "overwriting" the beginning of a longer string, the first thing to think of should be CR characters (used in Windows and Mac line endings). Command substitution removes newlines, but it removes Unix newlines (LF) and does nothing to carriage returns.

You can filter your input through tr -d '\r' to get rid of carriage returns, or use dos2unix utility to convert a broken file in-place.

Viewing your output with less -U can be helpful for debugging this kind of problems (less -U shows carriage returns, tabs and backspaces as control characters, like ^M ^I ^H).

Upvotes: 8

Related Questions