【问题标题】:Bash: Variable contains executable path -> Convert to stringBash:变量包含可执行路径->转换为字符串
【发布时间】:2018-06-14 01:04:09
【问题描述】:

我有这个问题,还没有找到足够的解决方案,也许你们可以帮助我。

我需要这样做:

find -name some.log

它会带来很多回击。所以现在我想用这样的“for”来完成它:

    for a in $(find -name vmware.log)
    do
      XXXXXXX
    done

之后,我想在变量 $a 中剪切路径。假设,$a 有以下内容:

./this/is/a/path/some.log

我将删除这个变量

cut -d/ -f2 $a

完成的代码是这样的:

for a in $(find -name vmware.log)
do
  cutpath=cut -d/ -f2 $a
done

当我这样做时,bash 使用 $a 的内容作为系统路径而不是字符串。所以“剪切”尝试直接访问文件,但它应该只剪切 $a 中的字符串路径。我在 VMware ESXi 上得到的错误是:

-sh: ./this/is/a/path/some.log: Device or resource busy

我做错了什么?谁能帮帮我?

【问题讨论】:

    标签: string bash variables cut esxi


    【解决方案1】:

    首先,不鼓励使用for 循环遍历find 的输出,因为它不适用于包含空格或全局元字符的文件名(例如*)。

    这实现了你想要的,使用-exec 开关。文件名{}$0 的形式传递给脚本。

    find -name 'vmware.log' -exec sh -c 'echo "$0" | cut -d/ -f2' {} \;
    # or with bash
    find -name 'vmware.log' -exec bash -c 'cut -d/ -f2 <<<"$0"' {} \;
    

    看起来您想对文件名使用 cut 而不是文件的内容,因此您需要将名称传递给标准输入,而不是作为参数。这可以使用管道 | 或使用 Bash 的 &lt;&lt;&lt; herestring 语法来完成。

    【讨论】:

    • 试过 :) 但没有运气。这里的输出:“find: -exec requires an argument” 我已经执行了这个:“find -name 'vmware.log' -exec bash -c 'echo "$0" | cut -d/ -f2' {} \"
    • @Sperk 如果您没有在末尾包含 \;,则表示您没有正确复制语法。
    • 对不起,我的错。我确实抄错了。它就像一个魅力。非常感谢:)
    【解决方案2】:

    你应该尝试使用这样的东西:

    #!/bin/bash
    
    VAR1="$1"
    VAR2="$2"
    
    MOREF='sudo run command against $VAR1 | grep name | cut -c7-'
    
    echo $MOREF
    

    使用引号将执行命令并将其存储在变量中。

    【讨论】:

    • 您好,感谢您的快速回答。我试图玩弄你的解决方案,但没有运气。你能解释一下吗?
    • 我建议使用MOREF=$(...)
    • 此答案中的代码不正确,似乎是直接从网上复制的exceptionshub.com/…
    猜你喜欢
    • 2012-11-23
    • 1970-01-01
    • 1970-01-01
    • 2011-04-20
    • 2020-12-22
    • 1970-01-01
    • 1970-01-01
    • 2013-05-18
    • 1970-01-01
    相关资源
    最近更新 更多