我正在开发一个小的shell脚本,用于将服务器日志备份到amazone。我们有多台服务器在生产中运行。所以我编写了一个动态检测服务器并进行备份的脚本。但是在比较两个字符串时我遇到了一个问题。我将在下面给出我写的代码片段和错误。
test.sh
host="$(hostname)"
if [ "$host" == "server1-myapp.com" ]; then
function_1 $host
elif [ "$host" == "server2-myapp.com" ]; then
function_2 $host
elif [ "$host" == "server3-myapp.com" ]; then
function_3 $host
fi
function_1 () {
echo "host name is $1"
}
function_2 () {
echo "host name is $1"
}
function_3 () {
echo "host name is $1"
}
但是当运行test.sh为 sh test.sh 时,我收到以下错误。
test.sh: 2: [: server1-myapp.com: unexpected operator
test.sh: 4: [: server1-myapp.com: unexpected operator
test.sh: 6: [: server1-myapp.com: unexpected operator
我尝试了不同的方法来匹配两个字符串,因为一个是变量,另一个是内联字符串,它不能正确匹配字符串,任何人都可以帮助我,我有点卡住了。
答案 0 :(得分:1)
将shell中的字符串与[ ]
运算符进行比较,它与=
而不是==
进行比较。这将有效:
if [ "$host" = "server1-myapp.com" ]; then