簡體   English   中英

在 Shell 腳本中執行另一個命令之前提示確認的命令

[英]Command to prompt for confirmation before executing another command in Shell script

我正在使用以下命令打開、替換、查看更改並保存文件:

sed 's/old string/new string/g' filename > filename1; diff filename1 filename; mv filename1 filename

在執行mv命令之前是否可以要求確認,如下所示?

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

目的是驗證更改,然后才保存它。

是的,你可以讀取用戶輸入通過可變read ,然后用一些可以接受的值進行比較,如"yes" 您也可以將命令存儲在變量中並將其打印給用戶並稍后執行。

#!/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

我的腳本是,

#!/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  

執行時的錯誤是,

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命令不起作用。

我在 bash 上使用了這個簡單的單襯:

echo -n 'Confirm: ' && read 'x' && [ $x == 'y' ] && <command>

這樣我不依賴於另一個實用程序,它只會在輸入為單個y時運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM