跳至正文
Shell Script to Check if a File Exists

Shell Script to Check if a File Exists

To check if a file exists in a shell script, you can use the test command or the [ command. Both commands are equivalent, but the test command is more powerful and allows you to perform more complex checks.

Here’s an example using the test command:

bash
if test -e {filename}; then
  echo "File exists"
else
  echo "File does not exist"
fi

Alternatively, you can use the [ command:

bash
if [ -e {filename} ]; then
  echo "File exists"
else
  echo "File does not exist"
fi

In both cases, replace {filename} with the name of the file you want to check.

You can also use the -f option to check if the file exists and is a regular file:

bash
if [ -f {filename} ]; then
  echo "File exists and is a regular file"
else
  echo "File does not exist or is not a regular file"
fi

Similarly, you can use the -d option to check if the file exists and is a directory:

bash
if [ -d {filename} ]; then
  echo "File exists and is a directory"
else
  echo "File does not exist or is not a directory"
fi

These are just a few examples of how you can check if a file exists in a shell script. You can find more options and examples in the test or [ command documentation.

本文共 215 字,以 CC 署名-非商业性使用-禁止演绎 4.0 国际 协议进行许可。

评论

博客助手

正在打开博客助手…