首页 > 解决方案 > Is my variable being overwritten in bash?

问题描述

I'm writing a shell script to do a git pull and increment the version of my web app hosted on ubuntu.

#!/bin/bash
#Date: September 10th, 2020
#Description: A shell script to pull the latest version to development, and increment the version
#
#Get current version from text file.
while IFS= read -r line; do echo "The current is: ${line}"; done < app-version.txt #${line} outputs version
#Prompt user for new version.
echo "Enter the new version and press [ENTER]."
read ver
#Increment version
echo "Updating Version to: ${ver}"
> app-version.txt
echo $ver > app-version.txt
#Pull latest version.
echo "Pulling files..."
git pull
echo "${ver}" #outputs version entered by user
echo "${line}" #outputs nothing
sed -i -e "s/${line}/${ver}/" sw-base-copy.js # sed: -e expression #1, char 0: no previous regular expression

app-version.txt is a one line text file that contains the current version, and is updated when the user enters a new version.

the ${line} variable echos properly in the while statement, but is blank when i run it as my regex in the sed command. Why?

标签: bashgitsed

解决方案


line gets overwritten on the second call to read (of the while loop) which determines that you have reached the end of the file. If app-version.txt is really a one-line file (or more importantly, you only care about the first line), you don't need a loop. Just read the first line:

#!/bin/bash

IFS= read -r line < app-version.txt
echo "The current is: $line"

echo "Enter the new version and press [ENTER]."
read ver
echo "Updating Version to: ${ver}"

echo "$ver" > app-version.txt

echo "Pulling files..."
git pull
sed -i -e "s/${line}/${ver}/" sw-base-copy.js

推荐阅读