8

有没有办法可以实现 find 或者 locate 输出的结果可以被后续命令处理?

 2 years ago
source link: https://www.v2ex.com/t/822496
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

V2EX  ›  Linux

有没有办法可以实现 find 或者 locate 输出的结果可以被后续命令处理?

  mylovesaber · 1 天前 · 848 次点击

已知有两个文件:test01 和 test0101

root@debian ~/test # ls t*
test01  test0101  t.sh

直接运行 find 命令的话,输出一切正常,但如果将 find 命令的输出结果赋值给一个新的变量,然后最终输出那个变量的话:

root@debian ~/test # cat t.sh
FIXED_PATH=$(find /root -name "*test01*")
${FIXED_PATH}

输出就是报错信息:

root@debian ~/test # bash t.sh 
t.sh: line 3: /root/test/test0101: Permission denied

什么原因导致的呢?有没有办法可以实现 find 或者 locate 输出的结果可以被后续命令处理?

9 条回复    2021-12-17 04:00:38 +08:00

ryd994

ryd994      1 天前 via Android   ❤️ 3

${FIXED_PATH} 的效果是执行这个命令
你需要的是 echo ${FIXED_PATH}
echo 是输出变量的内容

ETiV

ETiV      1 天前

处理啥?
find 一般后面接 xargs

mylovesaber

mylovesaber      1 天前

@ryd994 感谢提醒!看来我得早点睡觉了。。。。脑子浑了。。。

xiaoz

xiaoz      1 天前 via Android

find 不是自带后续处理命令吗用-exec

echoechoin

echoechoin      23 小时 42 分钟前

bash -x 可以调试嘛

Routeros

Routeros      23 小时 33 分钟前

[root@Aliyun ~]# find /root/ -name "main*"
/root/main.go
/root/main
/root/main.exe
[root@Aliyun ~]# cat t.sh
#!/bin/bash
FIXED_PATH=$(find /root/ -name "main*")
echo ${FIXED_PATH}
[root@Aliyun ~]# ./t.sh
/root/main.go /root/main /root/main.exe
[root@Aliyun ~]#

huntagain2008

huntagain2008      22 小时 12 分钟前

#1
#5
感谢上面 2 位的回答。本人非程序员,开始我以为是文件权限问题,可是楼主用的 root,应该无关。然后看了前面的回复我才搞懂了点。

楼主用的命令替换,用 shell 脚本将命令输出提取信息,并将其赋给变量。
其中一种将命令输出赋给变量:
$()格式 testing=$(date)
shell 会运行命令替换符号中的命令,并将其输出赋给变量 testing 。
楼主的情况就是 find 查找文件得到‘~/test/test01 ~/test/test0101 ’将其赋给 FIXED_PATH ,这一步是正确的。下一步使用变量 FIXED_PATH,楼主可能认为 find 命令得到的结果是一个数组,于是用了${FIXED_PATH},但我认为这不是数组,数组应该是(~/test/test01 ~/test/test0101)
> 你可能还见过通过${variable}形式引用的变量。变量名两侧额外的花括号通常用来帮助识别美元符后的变量名。

第二行${FIXED_PATH}实际就是~/test/test01 ~/test/test0101 我想应该是被解释为尝试执行~/test/test01 发现没有执行权限,如果再
$ chmod u+x ~/test/test01
这样给~/test/test01 加上执行权限,那么就不会报错了。

levinit

levinit      17 小时 11 分钟前 via iPhone

这不是 find 报错 很明显是执行那行 fixedpath 的问题 你先 echo 下那个 ficedpath ,看看输出啥,

cattyhouse

cattyhouse      7 小时 35 分钟前 via iPhone

FIXED_PATH=( $(find /root -name "*test01*") )
for i in ${FIXED_PATH[@]} ; do
[[ -x $i ]] && source $i
done

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK