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.

1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

4 Comments

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")
For sure, you never asked to. Just add -i switch. Post edited accordingly
Thank you! It worked. I will accept this answer in 5 minutes, when it allows me to.
It's probably worth noting that not every implementation of sed supports -i or supports it with no arguments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.