bash:尝试使用“$()”将“find”的输出放入变量中,但它不起作用

bash:尝试使用“$()”将“find”的输出放入变量中,但它不起作用

我的脚本的目的是根据用户输入提供的值提供最后一个子目录的完整路径。例如,以下脚本:

./script.sh TICKET-1234

应该输出类似这样的内容:

The full path is --> /share/data/TICKET-1234/some/other/sub/dir

我正在尝试使用以下代码来实现这一点:

rootPath="/share/data/"
anchorDir="${1}"
restOfPath=$(find /rootPath/$1/ -type d)
#fullPath=rootPath+anchorDir+restOfPath
echo "rest of path is $restofPath"

目前我只检查“ restOfPath”是否被分配了我期望的值 - 即TICKET-1234dir 下的所有剩余目录。但是,我得到以下输出:

./script.sh TICKET-1234
rest of path is /share/data/TICKET-1234/
/share/data/TICKET-1234/client
/share/data/TICKET-1234/client/region
/share/data/TICKET-1234/client/region/logs/
/share/data/TICKET-1234/client/region/logs/2019

如何仅捕获输出中最后一个路径的第二部分(“ /client/region/logs/2019”)并将其分配给$restOfPath变量?

谢谢

答案1

错误第 3 行:$rootPath 前面缺失。

答案2

应用建议的修复的结果shellcheck.net到你的脚本。

rootPath="/share/data/"
anchorDir="${1}"
restOfPath=$(find /rootPath/"$1"/ -type d)
#fullPath=rootPath+anchorDir+restOfPath
echo "rest of path is $restOfPath"

在应用更改之前检测到以下问题


Line 3:
rootPath="/share/data/"
^-- SC2034: rootPath appears unused. Verify use (or export if used externally).

Line 4:
anchorDir="${1}"
^-- SC2034: anchorDir appears unused. Verify use (or export if used externally).

Line 5:
restOfPath=$(find /rootPath/$1/ -type d)
^-- SC2034: restOfPath appears unused. Verify use (or export if used externally).
                            ^-- SC2086: Double quote to prevent globbing and word splitting.

Did you mean: (apply this, apply all SC2086)
restOfPath=$(find /rootPath/"$1"/ -type d)

Line 7:
echo "rest of path is $restofPath"
                      ^-- SC2154: restofPath is referenced but not assigned (did you mean 'restOfPath'?).

答案3

尝试这个,

find /rootPath/$1/  -type d -printf '/%P\n'
/
/client
/client/region
/client/region/logs
/client/region/logs/2019

如果我们只需要最后一行,

find /rootPath/$1/  -type d -printf '/%P\n' | tail -n1
/client/region/logs/2019

%P 文件的名称以及发现该文件已被删除的起始点的名称。

答案4

首先,find 命令缺少$符号。要仅获取最深的目录,您可以使用 find ,如下所示:

restOfPath=$(find $rootPath/$1 -type d -links 2)

您也可以尝试这种方式(这有点奇怪,但可以完成工作):

restOfPath=$(find $rootPath/$1 -type d |awk '{lnew=gsub(/\//,"/",$0); if (lnew > l) {l=lnew p=$0}; } END {print p}')

相关内容