'Appending file content to a String variable in loop within a bash file is not working
I am passing a text file to a bash while running. Text file has contents I want to supply to a java program as argument. Text file has each content in a new line. The contents print fine within the loop but I need to create a concatenated string with all the contents to pass to java program and appending to a string variable in loop is not working. This is how the program looks like:
#!/bin/bash
args=""
for var in $(cat payments.txt)
do
echo "Line:$var"
args+="$var "
done
echo "$args"
It prints:
Line: str1
Line:str2
str2 // args should have appended values of each line but it got only last line
File looks like:
str1
str2
Can anyone suggests what I am doing wrong here?
Thanks
Solution 1:[1]
Edit: the issue was due to \r\n line endings.
for var in $(cat payments.txt) is a nice example of useless use of cat. Prefer a while loop:
#!/bin/bash
args=""
while IFS= read -r var; do
args+="$var "
done < payments.txt
echo "$args"
But instead of looping, which is not very efficient with bash, you could as well use a bash array:
$ declare -a args=($(< payments.txt))
$ echo "${args[@]}"
str1 str2
"${args[@]}" expands as separate words. Use "${args[*]}" to expand as a single word . If your line endings are \r\n (Windows) instead of \n (recent macOS, GNU/Linux), the \r will interfere. To remove the \r before printing:
$ echo "${args[@]%$'\r'}"
Solution 2:[2]
Your first echo is printing out the combination and not storing it in a new variable. Try:
#!/bin/bash
args=""
for var in $(cat payments.txt)
do
echo = "Line:$var" # this line prints but doesn't alter $var
args+="Line:$var2 " #add Line: in here
done
echo "$args"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
