简体   繁体   English

使用命令行参数在Bash中检查文件是否存在

[英]Checking file existence in Bash using commandline argument

How do you use a command line argument as a file path and check for file existence in Bash? 如何使用命令行参数作为文件路径并检查Bash中文件的存在?

I have the simple Bash script test.sh : 我有简单的Bash脚本test.sh

#!/bin/bash

set -e
echo "arg1=$1"
if [ ! -f "$1" ]
then
    echo "File $1 does not exist."
    exit 1
fi
echo "File exists!"

and in the same directory, I have a data folder containing stuff.txt . 在同一目录中,我有一个包含stuff.txtdata文件夹。

If I run ./test.sh data/stuff.txt I see the expected output: 如果我运行./test.sh data/stuff.txt看到预期的输出:

arg1=data/stuff.txt
"File exists!"

However, if I call this script from a second script test2.sh , in the same directory, like: 但是,如果我从同一目录中的第二个脚本test2.sh调用此脚本,例如:

#!/bin/bash
fn="data/stuff.txt"
./test.sh $fn

I get the mangled output: 我得到错误的输出:

arg1=data/stuff.txt
 does not exist

Why does the call work when I run it manually from a terminal, but not when I run it through another Bash script, even though both are receiving the same file path? 为什么当我从终端手动运行该调用而不是通过另一个Bash脚本运行该调用时,即使两者都接收到相同的文件路径,该调用仍然起作用? What am I doing wrong? 我究竟做错了什么?

Edit: The filename does not have spaces. 编辑:文件名没有空格。 Both scripts are executable. 这两个脚本都是可执行的。 I'm running this on Ubuntu 18.04. 我正在Ubuntu 18.04上运行它。

The filename was getting an extra whitespace character added to it as a result of how I was retrieving it in my second script. 由于我在第二个脚本中检索文件名的结果,文件名中添加了一个额外的空格字符。 I didn't note this in my question, but I was retrieving the filename from folder list over SSH, like: 我没有在问题中注意到这一点,但是我正在通过SSH从文件夹列表中检索文件名,例如:

fn=$(ssh -t "cd /project/; ls -t data | head -n1" | head -n1)

Essentially, I wanted to get the filename of the most recent file in a directory on a remote server. 本质上,我想获取远程服务器上目录中最新文件的文件名。 Apparently, head includes the trailing newline character. 显然, head包含尾随的换行符。 I fixed it by changing it to: 我将其更改为:

fn=$(ssh -t "cd /project/; ls -t data | head -n1" | head -n1 | tr -d '\n' | tr -d '\r')

Thanks to @bigdataolddriver for hinting at the problem likely being an extra character. 感谢@bigdataolddriver暗示问题可能是额外的字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM