显示文件,如果它存在于给定的路径

问题描述:

我是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 
+1

你在找什么(正如下面的答案所解释的)被称为'文件测试操作员'。 – user1717259

+0

@ user1717259,是的!你是对的。 – MAK

#!/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. 
+2

标志不应该是-e,因为OP没有明确说输入是常规文件吗? – SilentMonk

+0

是的,我更新了我的答案。 –

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

-e =如果文件存在。 -f =如果文件存在并且是文件 – elcaos