因此,如果我的用户输入 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
这是一个 shell 函数,应该可以解决问题
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}";
}