tcsh检查文件是否存在于给定路径中

时间:2015-03-05 18:30:35

标签: user-input absolute-path tcsh

首先,我是tcsh的新手,我意识到它的缺点以及为什么它有害(我同意!)。

但是,我没有选择,我需要编写一个tcsh脚本,用户提供一个目录作为输入,脚本将检查它是否有文件' test.txt&#39 ;在它。

从技术上讲,子目录也会被标记为拥有它。

我假设这需要递归,我知道检查一个文件是否存在并且是一个我可以使用的常规文件

if ( ! -d $1) then
    echo $1 "is not a directory."
    exit 1
endif

if ( -f test.txt ) then    #BUT LINK IT TO $1, as if test.txt exists in 
                           #given user path or its parent directories

     echo "The path includes the file."
else
     echo "The path does NOT include the file."
endif

我希望能够检查$ 1 (这将是用户输入)。

1 个答案:

答案 0 :(得分:3)

您可以使用简单的while循环:

# Expand parameter to full path
set dir = `readlink -f "$1"`

# Not a directory? Stop now
if ( ! -d "$dir" ) then
    echo "$dir is not a directory."
    exit 1
endif

# Loop forever
while (1)
    # Check if $dir has test.txt, if it does, stop the loop
    if ( -f "$dir/test.txt" ) then
        echo "The path $dir includes the file."
        break
    else
        echo "The path $dir does NOT include the file."
        # Dir is /, we've checked all the dirs, stop loop and exit
        if ( "$dir" == "/" ) then
            echo "file not found, stopping"
            exit 2
            break
        endif

        # Remove last part of $dir, we use this value in the next loop iteration
        set dir = `dirname "$dir"`
    endif
end

echo "File found at $dir/test.txt"

逻辑应该是相当明显的:你为循环的每次迭代改变$dir的值,如果我们找到了文件,我们可以停止循环,如果我们循环的话到/目录,文件不存在,我们就停止了。您当然可以将/更改为cwd或其他内容......

示例输出:

[~]% csh checkdir.csh test/asd/asd/asd/asd/
The path /home/martin/test/asd/asd/asd/asd does NOT include the file.
The path /home/martin/test/asd/asd/asd does NOT include the file.
The path /home/martin/test/asd/asd does NOT include the file.
The path /home/martin/test/asd does NOT include the file.
The path /home/martin/test does NOT include the file.
The path /home/martin does NOT include the file.
The path /home does NOT include the file.
The path / does NOT include the file.
file not found, stopping
Exit 2

[~]% touch test/asd/asd/asd/test.txt
[~]% csh checkdir.csh test/asd/asd/asd/asd
The path /home/martin/test/asd/asd/asd/asd does NOT include the file.
The path /home/martin/test/asd/asd/asd includes the file.
File found at /home/martin/test/asd/asd/asd/test.txt

[~]% rm test/asd/asd/asd/test.txt
The path /home/martin/test/asd/asd/asd/asd does NOT include the file.
The path /home/martin/test/asd/asd/asd does NOT include the file.
The path /home/martin/test/asd/asd does NOT include the file.
The path /home/martin/test/asd does NOT include the file.
The path /home/martin/test does NOT include the file.
The path /home/martin includes the file.
File found at /home/martin/test.txt