程式扎記: [Linux 文章收集] Bash Shell: Check File Exists or Not

標籤

2015年7月12日 星期日

[Linux 文章收集] Bash Shell: Check File Exists or Not

Source From Here 
Preface 
How do I test existence of a text file in bash running under Unix like operating systems? 

You need to use the test command to check file types and compare values. The same command can be used to see if a file exist of not. 

The following command will tell if a text file called /etc/hosts exists or not using bash conditional execution: 
- test.sh 
  1. #!/bin/sh  
  2. [ -f /etc/hosts ] && echo "Found" || echo "Not found"  
Sample outputs: 
# ./test.sh
Found

The same code can be converted to use with if..else..fi which allows to make choice based on the success or failure of a test command: 
  1. #!/bin/bash  
  2. file="/etc/hosts"  
  3. if [ -f "$file" ]; then  
  4.     echo "$file found."  
  5. else  
  6.     echo "$file not found."  
  7. fi  
File test operators 
The following operators returns true if file exists: 
 

Supplement 
鳥哥 - 第十章、認識與學習BASH 
鳥哥 - 第十三章、學習 Shell Scripts

沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!