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

huangapple go评论62阅读模式
英文:

Need help to write shell script to check if file exist or not?

问题

I am trying to write a script which will tell if the file or directory exist or not. It will take the input "文件名" from the user.
First this will put the ls -l or ls output to a file and then take input from user (for filename), later will use if condition to check if file exist or not. But my code is not working.

# !/bin/bash
ls  > listtst.txt 
read -p "输入文件名" a
if [ -e "$a" ]; then
   echo "文件存在:$a"
else
   echo "文件不存在"
fi
英文:

I am trying to write a script which will tell if the file or directory exist or not. It will take the input " file name " from the user.
First this will put the ls -l or ls output to a file and then take input from user (for filename), later will use if condition to check if file exist or not. But my code is not working.

# !/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

得分: 2

要检查文件是否存在,您可以使用以下代码:

FILE=/var/scripts/file.txt
if [ -f "$FILE" ]; then
    echo "$FILE 存在"
else 
    echo "$FILE 不存在"
fi

将 "/var/scripts/file.txt" 替换为您的文件路径。

如果您需要文件路径作为变量,您可以将文件路径替换为 $1,这样您的代码将如下所示:

#!/bin/bash
if [ -f "$1" ]; then
    echo "$1 存在"
else 
    echo "$1 不存在"
fi

然后,您需要以以下方式调用您的脚本:

./scriptname.sh "文件路径"
英文:

To check if file exist or not you can use:

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

Replace "/var/scripts/file.txt" with your file path

in case you need the file path to be a variable

you can replace the file path with $1

so your code will be:

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

and you have to call your script in this way:

./scriptname.sh "filepath"

huangapple
  • 本文由 发表于 2020年1月3日 21:32:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/59579505.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定