Bashスクリプトは#1および#2パラメーターを使用しますが、ファイルが見つからない場合はユーザーから読み取りに戻ります。

Bashスクリプトは#1および#2パラメーターを使用しますが、ファイルが見つからない場合はユーザーから読み取りに戻ります。

したがって、ユーザーがbash copy.sh copysource.txt copydest.txtと入力し、ファイルが有効な場合は、copysourceをcopydestに追加してからcatを介してファイルを表示したいと思います。

- ファイル名が正しくないか見つからない場合... ユーザーに以下のコードを入力するように求めるメッセージを表示したいと思います。

#!/bin/bash
#Date: July 14 2016

if [ "$1" == "copysource.txt" ] && [ "$2" == "copydest.txt ]; then

cp $1 $2
echo "copies $1 to $2"
echo "contents of $2 are: "
cat $2

fi
#if the above was correct I want to script to stop
#otherwise if the info above was incorrect re: file names I want to user to be
#prompted to below code


clear
echo -n "Enter the source file name: "
read sourc


if [ "$sourc" == "copysource.txt" ]; then

    echo "The file name you entered was found!";

else
    echo "The file name you entered was invalid - please try again";
    echo -n "Enter the source file name: "
    read sourc
fi

echo -n "Enter the destination file name: "
read dest


if [ "$dest" == "copydest.txt" ]; then

    echo "The destination file name you entered was found!";

else
    echo "The destination file name you entered was invalid - please try         again";
    echo -n "Enter the destination file name: "
    read dest
fi


cp $sourc $dest
echo "copies $sourc to $dest"
echo "contents of $dest are: "
cat $dest

ベストアンサー1

以下のコードは、2つのファイル($ 1と$ 2に渡される)が存在することを確認し、$ 1を$ 2にリンクします(これはあなたが望むものだと思います)。ファイルのいずれかがまだ存在しない場合は、既存のファイルが入力されるまで、ソースファイルとターゲットファイル名を順番に入力するように求められます。それ以外の場合は、終了するにはCtrl-Cを押します。

#!/bin/bash
#Date: July 14 2016

# Use -f to test if files exist
if [[ -f "$1" ]] && [[ -f "$2" ]]; then
    echo "Appending contents of $1 to $2"
    # Use cat to take the contents of one file and append it to another
    cat "$1" >> "$2"
    echo "Contents of $2 are: "
    cat "$2"
    # Don't want to go any further so exit.
    exit
fi


# You could consider merging the logic above with that below
# so that you don't re-test both files if one of them exists, but the
# following will work.

clear
sourc=''
dest=''

while [[ ! -f "$sourc" ]]
do  
    echo -n "Enter the source file name: "
    read sourc

    if [ -f "$sourc" ]; then
        echo "The file name you entered was found!";
    else
        echo "The file name you entered was invalid - please try again";
    fi
done

while [[ ! -f "$dest" ]]
do
    echo -n "Enter the destination file name: "
    read dest

    if [ -f "$dest" ]; then
        echo "The file name you entered was found!";
    else
        echo "The file name you entered was invalid - please try again";
    fi
done

cat "$sourc" >> "$dest"
echo "Appending $sourc to $dest"
echo "Contents of $dest are: "
cat "$dest"

おすすめ記事