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
- #!/bin/sh
- [ -f /etc/hosts ] && echo "Found" || echo "Not 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:
- #!/bin/bash
- file="/etc/hosts"
- if [ -f "$file" ]; then
- echo "$file found."
- else
- echo "$file not found."
- fi
The following operators returns true if file exists:
Supplement
* 鳥哥 - 第十章、認識與學習BASH
* 鳥哥 - 第十三章、學習 Shell Scripts
沒有留言:
張貼留言