检查文件是否存在[BASH] [英] Check if file exists [BASH]

查看:150
本文介绍了检查文件是否存在[BASH]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查文件是否在bash的存在?

How do I check if file exists in bash?

当我尝试做这样的:

FILE1="${@:$OPTIND:1}"
if [ ! -e "$FILE1" ]
then 
    echo "requested file doesn't exist" >&2
    exit 1
elif
<more code follows>

我总是得到以下的输出:

I always get following output:

 requested file doesn't exist

使用该程序是这样的:

The program is used like this:

script.sh [-g] [-p] [-r FUNCTION_ID|-d FUNCTION_ID] FILE

任何想法吗?
我会很高兴的任何帮助。

Any ideas please? I will be glad for any help.

P.S。我希望我能显示整个文件,而无需从学校被解雇了有一个重复的风险。如果有沟通的私有方法,我会愉快地接受了他。

P.S. I wish I could show the entire file without the risk of being fired from school for having a duplicate. If there is a private method of communication I will happily oblige.

我的错。 FAS迫使一个二进制文件到一个错误的地方。感谢大家的帮助。

My mistake. Fas forcing a binary file into a wrong place. Thanks for everyone's help.

推荐答案

要(回顾),并添加到@ DavidW的出色答卷:

To (recap) and add to @DavidW.'s excellent answer:


  • 查看shebang行脚本的(第一行),以确保它是由庆典执行:这是#!/斌/庆典#!的/ usr / bin中/ env的庆典

  • Check the shebang line (first line) of your script to ensure that it's executed by bash: is it #!/bin/bash or #!/usr/bin/env bash?

检查对于隐藏控制字符脚本文件(如 \\ r ),可以导致意外的行为;运行猫-v脚本文件| fgrep一样^ - 它应该没有产生输出;如果该文件包含 \\ r 字符,它们将显示为 ^ M

Inspect your script file for hidden control characters (such as \r) that can result in unexpected behavior; run cat -v scriptFile | fgrep ^ - it should produce NO output; if the file does contain \r chars., they would show as ^M.


  • 要更精确地删除 \\ r 实例(,转换成Windows风格的 \\ r \\ n 新行序列Unix的 \\ n - 只序列),可以使用 DOS2UNIX的文件转换的;如果你没有这个工具,你可以使用 SED的/'$'\\ r''$ //'文件&gt; OUTFILE (警告:使用不同的输出文件,否则会破坏你的输入文件);删除的所有 \\ r 实例(即使不跟 \\ n ),使用 TR -d'\\ r'&LT;文件&gt; OUTFILE 。(警告:使用不同的输出文件,否则会破坏你的输入文件)

  • To remove the \r instances (more accurately, to convert Windows-style \r\n newline sequences to Unix \n-only sequences), you can use dos2unix file to convert in place; if you don't have this utility, you can use sed 's/'$'\r''$//' file > outfile (CAVEAT: use a DIFFERENT output file, otherwise you'll destroy your input file); to remove all \r instances (even if not followed by \n), use tr -d '\r' < file > outfile (CAVEAT: use a DIFFERENT output file, otherwise you'll destroy your input file).

  • 在除了@ DavidW的伟大调试技术,您可以添加以下为目视检查所有的参数传递给脚本:

  • In addition to @DavidW.'s great debugging technique, you can add the following to visually inspect all arguments passed to your script:
i=0; for a; do echo "\$$((i+=1))=[$a]"; done 

(封闭的价值的目的 [...] (例如),就是看值的确切边界。)

(The purpose of enclosing the value in [...] (for example), is to see the exact boundaries of the values.)

这将产生类似:

$1=[-g]
$2=[input.txt]
...

请注意,虽然,什么都没有打印,如果没有参数被传递。

Note, though, that nothing at all is printed if no arguments were passed.

这篇关于检查文件是否存在[BASH]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆