显示文件是否存在于给定路径中

时间:2016-05-31 13:40:54

标签: bash shell unix

我是Unix shell脚本的新手。

我创建了一个文件,它将一个参数作为文件名,以便在文件的给定路径中找到。如果找到该文件,则应显示该文件或显示相应的消息。

档案FilePath.sh

#!/bin/sh

Given_Path=/user/document/workplace/day1

File_Name=$Given_Path/$1

# Here i got stuck to write the if condition,
# to check for the file is present in the given 
# path or not.
if [---------] #Unable to write condition for this problem.
then
    echo $1
else
    echo "File not found"
fi

运行:运行文件

$ bash FilePath.sh File1.txt

2 个答案:

答案 0 :(得分:8)

#!/bin/sh

Given_Path=/user/document/workplace/day1

File_Name=$Given_Path/$1

#Check if file is present or not.

if [ -e "$File_Name" ] 
then
    echo $1
else
    echo "File not found"
fi

一些一般条件:

-b file = True if the file exists and is block special file. 
-c file = True if the file exists and is character special file. 
-d file = True if the file exists and is a directory. 
-e file = True if the file exists. 
-f file = True if the file exists and is a regular file 
-g file = True if the file exists and the set-group-id bit is set. 
-k file = True if the files' "sticky" bit is set. 
-L file = True if the file exists and is a symbolic link. 
-p file = True if the file exists and is a named pipe. 
-r file = True if the file exists and is readable. 
-s file = True if the file exists and its size is greater than zero. 
-s file = True if the file exists and is a socket. 
-t fd = True if the file descriptor is opened on a terminal. 
-u file = True if the file exists and its set-user-id bit is set. 
-w file = True if the file exists and is writable. 
-x file = True if the file exists and is executable. 
-O file = True if the file exists and is owned by the effective user id. 
-G file = True if the file exists and is owned by the effective group id. 
-n $var = Uninitialized variable is true.

答案 1 :(得分:2)

if [ -e "filename" ]
then
    echo $1
else
    echo "File not found"
fi