简体   繁体   中英

Replace variable in bash file using sed - output lags

I'm trying to write a bash script that search and replace a specific user input saved in config.sh using sed. This does work; however it only works partially as shown below.

config.sh

 #!/bin/bash # #UserName to be deleted delUserName="" #Source delUserSrc=/Users/"$delUserName" #Destination delUserDest=/Users/John/BackUp/"$delUserName"/"$delUserName".zip 

main.sh

 #!/bin/bash # source scripts/config.sh echo -e "\\nEnter user you wish to delete: \\c" read -r UserName sed -i '' -e "s/delUserName=.*/delUserName=$UserName/g" scripts/config.sh echo -e "delUserName: $delUserName" echo -e "delUserSrc: $delUserSrc" echo -e "delUserDest: $delUserDest" 

output1:

 Enter user you wish to delete: Test delUserName: delUserSrc:/Users/ delUserDest:/Users/John/BackUp/ / .zip 

output2:

 Enter user you wish to delete: Test1 delUserName:Test delUserSrc:/Users/Test delUserDest:/Users/John/BackUp/Test/Test.zip 

output3:

 Enter user you wish to delete: Test1 delUserName:Test1 delUserSrc:/Users/Test1 delUserDest:/Users/John/BackUp/Test1/Test1.zip 

expected output1:

 Enter user you wish to delete: Test delUserName:Test delUserSrc:/Users/Test delUserDest:/Users/John/BackUp/Test/Test.zip 

expected output2:

 Enter user you wish to delete: Test1 delUserName:Test1 delUserSrc:/Users/Test1 delUserDest:/Users/John/BackUp/Test1/Test1.zip 

The script lags. sed instantaneously changed the value for $delUserName BUT The proper values for $delUserName, $delUserSrc, and $delUserDest only echo on the 2nd run. The scripts run well when all variables are in main.sh except i have to do it this way. Save the user input into $UserName. Any idea why the values don't show when run the 1st time? Thanks

Here is what I think is happening.

The sed command replaces text in files. It does not modify the value of variables in memory. These values are assigned when you source config.sh .

So right after your sed line, you need to put this line :

source scripts/config.sh

It is the same line as above in your script. This is required there also so that your newly replaced values will be loaded in the variables so that you can display them. Once the new values are loaded in memory, then the echo statements will be able to expand the variables to that new value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM