如何使用bash文件查找文件是否存在?

时间:2019-05-06 20:22:00

标签: linux bash file

我正在尝试完成一些代码(希望)在没有给出任何参数的情况下(希望)接受用户的输入,并查找文件是否存在,然后创建备份,以便他们可以自由编辑,如果没有输入,也可以进行同样的操作加上使用“读取”获取文件名。目前,我发现尽管未使用该变量,但是否正在触发[-f $ file named]。

我曾尝试将-f更改为-e,但这并没有帮助我也尝试在调用该节之前使名为= no的变量文件成为文件,但尽管不满足要求,它仍会触发if语句。

#!/bin/bash

if ["$2" != "" ]
then
 echo "Only input one parameter and try again" && exit 0
fi

#if no command line parameter is given prompt for a file name
if [ "$1" == "" ]
then
 echo "what is the file name? " && read filecalled
fi

# checks if the file name given exists if it does backup and open in vim
if [ -f $filecalled ]
then
>  echo "File has been located" && echo "making a backup and opening the >editor" && cp "$filecalled" "$filecalled.bak" && vim "$filecalled" && exit 0
#If there was a parameter given, is it a real file if yes back up and open in vim
elif [ -f $1 ]
then
  echo "File has been located" && echo "Making a backup and opening an editor" && cp "$1" "$1.bak" && vim "$1" && exit 0
if there was no valid file name in either then open a new file in vim
else
 echo "There was no file located, opening vim" && vim && exit 0
fi

我放置的位置“>”似乎是我遇到最多问题的地方。我的理想结果是将文件与存在的文件进行检查(在/ Desktop上使用它来控制存在的文件),如果它们确实存在,则可能发生其他事情。 谢谢

0 个答案:

没有答案
相关问题