我已经设法弄清楚如何测试目录和可靠性,但是在我尝试使用ssh上的远程服务器执行此操作时会遇到问题。测试/ tmp目录的第一个实例工作正常,但是当调用第二部分时,我得到line 0: [: missing
]'`
现在,如果我用单引号替换\“,它可以工作,但我认为单引号变量引用?有人可以解释一下这个吗?假设tmp目录确实存在并且是可写的,到目前为止这是脚本
#!/bin/bash
SshHost="hostname"
SshRsa="~/.ssh/id_rsa"
SshUser="user"
SshPort="22"
Base="/tmp"
Sub="one space/another space"
BaseBashExist="bash -c \"[ -d \"$Base\" ] && echo 0 && exit 0 || echo 1 && exit 1\""
SSHBaseExist=$( ssh -l $SshUser -i $SshRsa -p $SshPort $SshHost ${BaseBashExist} )
echo -n $Base
if [ $? -eq 0 ]
then
echo -n "...OK..."
else
echo "...FAIL"
exit 1
fi
BaseBashPerm="bash -c \"[ -w \"$Base\" ] && echo 0 && exit 0 || echo 1 && exit 1\""
SSHBaseExist=$( ssh -l $SshUser -i $SshRsa -p $SshPort $SshHost ${BaseBashPerm} )
if [ $? -eq 0 ]
then
echo "...writeable"
else
echo "...not writeable"
fi
BaseAndSub="$Base/$Sub"
BaseAndSubBashExist="bash -c \"[ -d \"$BaseAndSub\" ] && echo 0 && exit 0 || echo 1 && exit 1\""
SSHBaseAndSubExist=$( ssh -l $SshUser -i $SshRsa -p $SshPort $SshHost ${BaseAndSubBashExist} )
echo -n $BaseAndSub
if [ $? -eq 0 ]
then
echo -n "...OK..."
else
echo "...FAIL"
exit 1
fi
BaseAndSubBashPerm="bash -c \"[ -w \"$BaseAndSub\" ] && echo 0 && exit 0 || echo 1 && exit 1\""
SSHBaseAndSubPerm=$( ssh -l $SshUser -i $SshRsa -p $SshPort $SshHost ${BaseAndSubBashPerm} )
if [ $? -eq 0 ]
then
echo -n "...writeable"
else
echo "...not writeable"
fi
exit 0
答案 0 :(得分:2)
你应该做的第一件事就是简单地重构你的代码,然后引用错误也会消失。尝试:
if ssh [flags] test -w "'$file'"; then
将您的SSH标记封装在ssh配置中以方便重复使用,您的脚本将会大幅缩短。
答案 1 :(得分:1)
在这种情况下你可以使用单引号;当远程bash看到脚本时,你的本地bash已经替换了你想要替换的变量。
然而,你的脚本是一团糟。如果你不能大大简化它,你应该把重复的代码放在函数中。
#!/bin/bash
remote () {
# most of the parameters here are at their default values;
# why do you feel you need to specify them?
#ssh -l "user" -i ~/.ssh/id_rsa -p 22 hostname "$@"
ssh hostname "$@"
# —---------^
# if you really actually need to wrap the remote
# commands in bash -c "..." then add that here
}
exists_and_writable () {
echo -n "$1"
if remote test -d "$1"; then
echo -n "...OK..."
else
echo "...FAIL"
exit 1
fi
if remote test -w "$1"; then
echo "...writeable"
else
echo "...not writeable"
fi
}
Base="/tmp"
# Note the need for additional quoting here
Sub="one\\ space/another\\ space"
exists_and_writable "$Base"
BaseAndSub="$Base/$Sub"
exist_and_writable "$BaseAndSub"
exit 0
答案 2 :(得分:-1)
let queue = DispatchQueue(label: "name_queue", qos: .background)
queue.async {
DispatchQueue.main.sync {
// do anything
}
}