3

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.

3 Answers 3

6

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.

2
  • You can make it shorter: read -p "confirm: " x; [ "$x" = "y" ] && <command> :)
    – myrdd
    Commented Jul 8, 2023 at 9:11
  • If you're using fish, write [ "$(read -P 'confirm: ')" = 'y' ]; and <command>
    – myrdd
    Commented Jul 8, 2023 at 9:29
2

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
1
  • it didn't work out...i will paste the issue as answer as here formatting is so bad
    – Thangan
    Commented Feb 21, 2015 at 17:19
0

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.

4
  • Some space characters are important to have, and you are missing many. For example [[ and ]] require spaces around.
    – svlasov
    Commented Feb 21, 2015 at 17:54
  • One last thing what's the command to search for a word and display the whole line (where the word present)....Thanks....
    – Thangan
    Commented Feb 21, 2015 at 18:12
  • It's grep. grep word some/file
    – svlasov
    Commented Feb 21, 2015 at 18:16
  • 1
    Unless it's related, better to ask a new question.
    – svlasov
    Commented Feb 21, 2015 at 18:27

Not the answer you're looking for? Browse other questions tagged or ask your own question.