Shell 如果文件或目录存在,则覆盖
我不熟悉shell脚本。如果文件或目录(文件夹)存在,则脚本应覆盖它;如果它不存在,那么它应该创建一个新的文件或目录 这就是我尝试过的:Shell 如果文件或目录存在,则覆盖,shell,Shell,我不熟悉shell脚本。如果文件或目录(文件夹)存在,则脚本应覆盖它;如果它不存在,那么它应该创建一个新的文件或目录 这就是我尝试过的: #!/bin/bash unset File unset Directory echo -n "File:" read File echo -n "Directory:" read Directory if [ -f "$File" ]; then echo "file $File exist. Do you want overwrite it? (
#!/bin/bash
unset File
unset Directory
echo -n "File:"
read File
echo -n "Directory:"
read Directory
if [ -f "$File" ]; then
echo "file $File exist. Do you want overwrite it? (y/n)"
read yn
if [ $yn = "N" -o $yn = "n"];
then
exit 0
fi
echo "$File" >> testfile
else
echo "file Does not exist"
touch $File
fi
if [ -d "$Directory" ]; then
echo "directory $directory exist.Do you want overwrite it? (y/n)"
read yn
if [ $yn = "N" -o $yn = "n" ];
then
exit 0
else
echo "directory Does not exist"
mkdir -p $Directory
fi
fi
我需要做哪些更改才能获得所需的行为
echo "$File" >> testfile
上面的行“追加”到名为“testfile”的文件中。它不会覆盖有问题的文件,即$file
if [ -d "$Directory" ]; then
if [ $yn = "N" -o $yn = "n" ];
then
exit 0
else
fi
fi
在这一部分中,您需要将'else'子句添加到外部if,而不是内部if,以处理目录不存在的情况。
此外,如果存在名为“$Directory”的普通文件,则“[-d”$Directory”]”测试将返回false。在这种情况下,创建同名目录的尝试将失败。是的,您经常这样做。那么,你的问题是什么?到目前为止你做了哪些尝试?请将您的代码添加到您的问题中。有关如何在Stackoverflow上操作的详细信息,请参阅。对于文件,您可以这样做:“>文件路径”。如果存在,则覆盖;如果不存在,则创建。对于目录,如果其中有文件,则需要定义覆盖的含义。是否只想删除所有文件?您需要编辑问题以定义所需的行为。您需要学习如何调试shell脚本(
bash-x脚本
或sh-x脚本
或您使用的任何shell的等效脚本)。