需要帮助编写Shell脚本来检查文件是否存在?

时间:2020-01-03 13:32:12

标签: linux bash

我正在尝试编写一个脚本,该脚本将告诉文件或目录是否存在。它将接受用户输入的“文件名”。 首先,这会将ls -lls的输出放入文件中,然后从用户那里获取输入(用于文件名),然后将使用if条件检查文件是否存在。但是我的代码无法正常工作。

# !/bin/bash
ls  > listtst.txt 
read -p "type file name" a
if [ listtst.txt  ==  $a  ];
  then
     echo "file is present $a"
  else
    echo "file not present"
fi

1 个答案:

答案 0 :(得分:1)

要检查文件是否存在,可以使用:

FILE=/var/scripts/file.txt
if [ -f "$FILE" ]; then
    echo "$FILE exist"
else 
    echo "$FILE does not exist"
fi

用文件路径替换“ /var/scripts/file.txt”

如果您需要文件路径为变量

您可以将文件路径替换为$ 1

因此您的代码将是:

#!/bin/bash
if [ -f "$1" ]; then
    echo "$1 exist"
else 
    echo "$1 does not exist"
fi

,您必须以这种方式调用脚本:

./scriptname.sh "filepath"