1

I have a bash script that loops over a set of files, and replaces a string, in each file, with a version number.

#!/bin/bash

ANGULAR_APP_VERSION=6.6.6
echo $ANGULAR_APP_VERSION

declare -a arr=(
"test1.txt" 
"test2.txt"
)

for i in "${arr[@]}"
do
  sed 's/"@@BUILD_VERSION@@"/"'$ANGULAR_APP_VERSION'"/g' ${arr[$i]}
done

Everytime I run the script, it generates the following error:

./test1.txt: syntax error: operand expected (error token is "./test1.txt")

I don't understand why it is wrong. The files exist.

Gilles Quenot
  • 143,367
  • 32
  • 199
  • 195
Nicolas El Khoury
  • 3,421
  • 3
  • 14
  • 19
  • see also https://stackoverflow.com/questions/7680504/sed-substitution-with-bash-variables which is one of the faqs listed in https://stackoverflow.com/tags/sed/info – Sundeep Apr 02 '18 at 12:37

1 Answers1

3
#!/bin/bash

ANGULAR_APP_VERSION="6.6.6"
echo "$ANGULAR_APP_VERSION"

arr=(
    "test1.txt" 
    "test2.txt"
)

for i in "${arr[@]}"; do
     sed -i "s/@@BUILD_VERSION@@/$ANGULAR_APP_VERSION/g" "$i"
done

($i is each value of the array one at a time in the iteration)

or using array key :

for i in "${!arr[@]}"; do
     sed -i "s/@@BUILD_VERSION@@/$ANGULAR_APP_VERSION/g" "${arr[i]}"
done

Learn how to quote properly in shell, it's very important :

"Double quote" every literal that contains spaces/metacharacters and every expansion: "$var", "$(command "$var")", "${array[@]}", "a & b". Use 'single quotes' for code or literal $'s: 'Costs $5 US', ssh host 'echo "$HOSTNAME"'. See http://mywiki.wooledge.org/Quotes
http://mywiki.wooledge.org/Arguments
http://wiki.bash-hackers.org/syntax/words

Gilles Quenot
  • 143,367
  • 32
  • 199
  • 195
  • Using: sed "s/@@BUILD_VERSION@@/$ANGULAR_APP_VERSION/g" "$i" works, but it doesn't update the files, it just prints out the modified sring using: sed "s/@@BUILD_VERSION@@/$ANGULAR_APP_VERSION/g" "${arr[i]}" generates the following: test1.txt: syntax error: invalid arithmetic operator (error token is ".txt") – Nicolas El Khoury Apr 02 '18 at 12:25
  • For sure, you never asked to. Just add `-i` switch. Post edited accordingly – Gilles Quenot Apr 02 '18 at 12:26
  • 1
    Thank you! It worked. I will accept this answer in 5 minutes, when it allows me to. – Nicolas El Khoury Apr 02 '18 at 12:28
  • It's probably worth noting that not every implementation of `sed` supports `-i` or supports it with no arguments – Eric Renouf Apr 02 '18 at 12:39