【问题标题】:How to run binary using path with backslash stored in variable?如何使用存储在变量中的反斜杠路径运行二进制文件?
【发布时间】:2021-10-27 11:50:23
【问题描述】:
$ cat test.sh
#! /bin/bash

if [ -f /home/amnesia/Persistent/yubikey-manager-qt.AppImage ]; then
  ykman="/home/amnesia/Persistent/yubikey-manager-qt.AppImage ykman"
elif [ -f /Applications/YubiKey\ Manager.app/Contents/MacOS/ykman ]; then
  ykman="/Applications/YubiKey\ Manager.app/Contents/MacOS/ykman"
else
  printf "$bold$red%s$normal\n" "Could not find YubiKey Manager binary"
  exit 1
fi

$ykman list

$ test.sh
./test.sh: line 12: /Applications/YubiKey\: No such file or directory

./test.sh: line 12: /Applications/YubiKey: No such file or directory

如何解决上述错误?

使用以下方法解决了 macOS 上的问题,但由于 ykman AppImage 要求而破坏了 Tails 上的问题。

$ cat test.sh
#! /bin/bash

if [ -f /home/amnesia/Persistent/yubikey-manager-qt.AppImage ]; then
  ykman="/home/amnesia/Persistent/yubikey-manager-qt.AppImage ykman"
elif [ -f /Applications/YubiKey\ Manager.app/Contents/MacOS/ykman ]; then
  ykman="/Applications/YubiKey Manager.app/Contents/MacOS/ykman"
else
  printf "$bold$red%s$normal\n" "Could not find YubiKey Manager binary"
  exit 1
fi

"$ykman" list

$ test.sh
./test.sh: line 12: /home/amnesia/Persistent/yubikey-manager-qt.AppImage ykman: No such file or directory

./test.sh: line 12: /home/amnesia/Persistent/yubikey-manager-qt.AppImage ykman: No such file or directory

感谢您的帮助!

【问题讨论】:

  • 使用函数而不是变量。 ykman() { /Applications/YubiKey\ Manager.app/Contents/MacOS/ykman "$@"; }
  • 您没有删除示例中的反斜杠
  • 不。空格是IFS 默认值的一部分。如果您不引用变量,bash 将在每个空格上拆分。您唯一的解决方案是覆盖 IFS 变量的值(这将对脚本的其余部分产生影响,因此如果您选择这样做,请确保您正在执行的操作)
  • 我还是推荐一个函数来跳过那些陷阱。
  • 尝试输入ls "/Applications/YubiKey Manager":你会看到空间没有被分割。在这里,您需要引号,因为您正在评估您的命令 2 次:1)将值分配给变量 2)当您将变量作为命令调用时。每次评估您的内容时都需要双引号。关于你的问题:空间没有分裂,因为它被转义了

标签: linux bash macos


【解决方案1】:

您应该引用变量取消引用以避免变量中的空格被解释为空格分隔多个值。

ykman="Application/YubiKey Manager.app/Contents/test.sh"
#use quotes while running 
./"$ykman"
test script output

【讨论】:

  • 感谢您的帮助。不幸的是,这并不总是有效……请参阅改进的问题。
猜你喜欢
  • 2012-08-30
  • 2013-07-23
  • 1970-01-01
  • 2014-02-04
  • 2017-03-16
  • 2015-03-24
  • 1970-01-01
  • 2019-08-06
相关资源
最近更新 更多