How do I test if bash performed a string replacement?
Linux - NewbieThis Linux forum is for members that are new to Linux.
Just starting out and have a question?
If it is not in the man pages or the how-to's this is the place!
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
#!/bin/bash
string=Not_Changed
#first change the string then check it
string2=${string/Not_/Was_}
if [[ "$string" == "$string2" ]];
then #Did a replacement occur?
echo "Not changed: $string" #no
else
echo "changed: $string2" #yes
fi
If statements ALWAYS test (for) true, else you'll throw an error.
Code:
if [[ "$string" != "$string2" ]];
then #Did a replacement occur?
echo "changed: $string2" #yes
else
echo "Not changed: $string" #no
fi
I was unclear about my goal in my post. I apologize.
I'm trying to understand what capabilities bash offers with its conditionals (what operations can the "if" test).
Can the "if" detect the execution of a string operation which occurs within the "if" statement?
Hello BW-userx and ondoho,
Thank you for the responses.
I read your link, did more searches, and did more tests.
It appears that you are correct, ondoho. I can't execute a command within a bash conditional. (Pity. I was hoping bash would be similar to perl.)
That explains why I couldn't find references in my online searches (trying to find something that you can't do).
You can definitely run cmds inside an if [[ ]] statement, but in this case you are testing the result of the cmd (ie if it failed or not), NOT the whether the data was changed.
IOW, some cmds only rtn other-than-zero if they actually failed ie crashed or equiv.
If they 'ran ok', it doesn't actually mean they did what you expected.
Remember a cmd is just a program.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.