gpt4 book ai didi

user-input - tcsh 检查给定路径中是​​否存在文件

转载 作者:行者123 更新时间:2023-12-02 03:32:34 25 4
gpt4 key购买 nike

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

但是,我别无选择,我需要编写一个 tcsh 脚本,其中用户提供一个目录作为输入,脚本将检查其中是否包含文件“test.txt”。

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

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

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(这将是用户输入)。

最佳答案

您可以使用简单的 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

关于user-input - tcsh 检查给定路径中是​​否存在文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28885142/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com