따라서 사용자가 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
아래 코드는 두 개의 파일($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"
답변2
트릭을 수행해야 하는 쉘 함수는 다음과 같습니다.
appendFile(){
local iFile oFile;
[ ! -f "$1" ] || [ -z "$2" ] && {
while [ ! -f "$iFile" ]; do read -p "Input file: " -i "$1" iFile; done;
read -i "$2" -p "Output file: " oFile;
};
cat "${iFile-$1}" >> "${oFile-$2}";
cat "${oFile-$2}";
}