英文:
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"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论