bash - 带有前置字符的 Bash if 语句
问题描述
我试图理解一个以root身份执行时将停止的脚本:
#!/usr/bin/env bash
if [ x"$(whoami)" = x"root" ]; then
echo "Error: don't run this script as root"
exit 1
fi
我已经对此进行了测试,即使我x
在 if 语句中删除了它,它也能按预期工作。我的问题是为什么x
inx"$(whoami)"
和x"root"
需要?
解决方案
basically the [ is a softlink to an external program called test, therefore the condition is passed to it as program arguments, and doing so if you don't surround a $variable with "$quotes" , and the variable happens to be empty it won't be considered as an empty argument, it will be considered as no argument (nothing)
#!/bin/bash -eu
var=bla
if [[ $var == bla ]];then
echo first test ok
fi
var=""
if [[ $var == "" ]];then
echo second test ok
fi
if [ "$var" == "" ];then
echo third test ok
fi
if [ x$var == "x" ];then
echo fourth test ok
fi
echo this will fail:
if [ $var == "" ];then
echo fifth test ok
fi
echo because it is the same as writing:
if [ == "" ];then
echo sixth test is obviously eroneous
fi
echo but also you should quote your variables because this will work:
var="a b"
if [ "$var" == "a b" ];then
echo seventh test ok
fi
echo ... but this one won\'t as test now has four arguments:
if [ $var == "a b" ];then
echo eighth test ok
fi
推荐阅读
- go - "transaction type not supported" When trying to deploy a simple contract using Go-Ethereum, Solidity, Go. Doesn't happen in Remix
- amazon-web-services - Assistance with Header based routing with AWS App Mesh
- java - How to have different color for line and text in StrikethroughSpan?
- python - Problem with grouping and counting in python
- google-apps-script - How to import csv file from the link in gmail to google sheet with apps script?
- github - Can I prevent Github Actions from updating status checks?
- python - Python-Z3:Python 的断言不成立
- scala - 如何在 Azure 数据工厂链接服务中设置 spark 执行器内存
- java - How to improve performance of String.split?
- excel - Is it possible to make a number sequence based on a condition?