Reputation: 43
I am using below command to open, replace, view the change and save a file:
sed 's/old string/new string/g' filename > filename1; diff filename1 filename; mv filename1 filename
Is it possible to ask for a confirmation before executing mv
command, something like below?
sed 's/old string/new string/g' filename > filename1
diff filename1 filename
<Some-Command here for user to provide Yes or NO confirmation>
mv filename1 filename
The intent is to validate the change and only then save it.
Upvotes: 3
Views: 3940
Reputation: 23200
I use this simple one liner on bash:
echo -n 'Confirm: ' && read 'x' && [ $x == 'y' ] && <command>
.
This way I do not depend on another utility and it will run only when input is single y
.
Upvotes: 6
Reputation: 43
My Script is ,
#!/bin/bash
sed 's/This/It/g' test.xml > "test.xml1"
diff test.xml test.xml1
COMMAND ='mv test.xml1 test.xml'
echo "Perform the following command:"
echo
echo " \$ $COMMAND"
echo
echo -n "Answer 'yes' or 'no':"
read REPLY
if[[$REPLY=="yes"]]; then
$COMMAND
else
echo Aborted
exit 0
fi
The error on executing is,
2c2
< This is a Test file
---
> It is a Test file
./test.sh[9]: COMMAND: not found
Perform the following command:
$
-n Answer 'yes' or 'no':
yes
./test.sh[19]: syntax error at line 20 : `then' unexpected
mv
command didn't work.
Upvotes: 0
Reputation: 10456
Yes, you can read user input into a variable via read
, and then compare with some acceptable value, like "yes"
. Also you can store the command in the variable and print it to user and execute it later.
#!/bin/bash
COMMAND='mv filename1 filename'
echo "Perform the following command:"
echo
echo " \$ $COMMAND"
echo
echo -n "Answer 'yes' or 'no': "
read REPLY
if [[ $REPLY == "yes" ]]; then
$COMMAND
else
echo Aborted
exit 0
fi
Upvotes: 2