2016-05-31 51 views
1

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

回答

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

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

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

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

相關問題