1

我在 if 语句的 != 部分遇到了一些问题。据我所知,基本上这个语句是有效的,但是执行它会给出[: 1: !=: unexpected operator. 我尝试使用 -n 执行,但无论出于何种原因,即使输出为空白,使用 -n 仍会运行 echo 命令。

对此的任何帮助表示赞赏。我附上了下面的代码片段。

#!/bin/sh

HOST=$1
USER="/scripts/whoowns $HOST | tr -d '\r'"

ssh -t $HOST -p 22 -l deehem "sh -c 'if [ "" != "\`$USER\`" ]; then echo "Username for $HOST: \`$USER\`"; fi' ; bash -login"
4

2 回答 2

0

正如您所意识到的,"bla "" bla"只是连接了两个字符串 ( "bla bla")。

您可以转义": \",但标准[ test工具有一个专门用于此任务的选项:

   -n STRING
          the length of STRING is nonzero

   -z STRING
          the length of STRING is zero

注意:为什么你有\`?这样字符串永远不会为空....

于 2013-03-20T21:51:42.763 回答
0

关于您的“但是执行此操作会给出[: 1: !=: unexpected operator”问题,这是一个解决方案:

使用bash -c而不是sh -c. bash 程序在处理方括号方面似乎比 sh 更好。例如:

ubuntu@ubuntu:/$ echo "antipetalous" | if [[ "antipetalous" =~ "ti" ]]; then echo "match"; else echo "no"; fi
match
ubuntu@ubuntu:/$ echo "antepetalous" | if [[ "antepetalous" =~ "ti" ]]; then echo "match"; else echo "no"; fi
no
ubuntu@ubuntu:/$ sh -c 'echo "antipetalous" | if [[ "antipetalous" =~ "ti" ]]; then echo "match"; else echo "no"; fi'
sh: 1: [[: not found
no
ubuntu@ubuntu:/$ bash -c 'echo "antipetalous" | if [[ "antipetalous" =~ "ti" ]]; then echo "match"; else echo "no"; fi'
match
ubuntu@ubuntu:/$ bash -c 'echo "antepetalous" | if [[ "antepetalous" =~ "ti" ]]; then echo "match"; else echo "no"; fi'
no
ubuntu@ubuntu:/$ sh -c 'echo "antepetalous" | if [[ "antepetalous" =~ "ti" ]]; then echo "match"; else echo "no"; fi'
sh: 1: [[: not found
no
ubuntu@ubuntu:/$

所以ssh -t $HOST -p 22 -l deehem "sh -c 'if [ "" != ...会变成ssh -t $HOST -p 22 -l deehem "bash -c 'if [ "" != ....

感谢 pLumo 在https://askubuntu.com/questions/1310106/sh-c-sh-not-working-when-using-if-statement-and-having-in-the-filena(“命令行 - sh - c '...' sh {} 在使用 if 语句并且文件名中有 ' 时不起作用 - Ask Ubuntu")。

于 2022-02-08T03:19:27.943 回答