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

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...