“x$VARIABLE"中 x 的 shell 脚本目的 [英] shell script purpose of x in "x$VARIABLE"

查看:28
本文介绍了“x$VARIABLE"中 x 的 shell 脚本目的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看一些 shell 脚本 - comarison shcu as 中 x 的目的是什么

I'm peeking through some shell scripts - what's the purpose of the x in the comarison shcu as

 if [ "x$USER" != "x$RUN_AS_USER" ]; then
        su - $RUN_AS_USER -c "$CATALINA_HOME/bin/startup.sh"
 else
        $CATALINA_HOME/bin/startup.sh
 fi

推荐答案

如果其中一个变量为空,这是一个确保在替换中不会得到空字符串的技巧.将 x 放在两边与直接比较变量是一样的,但两边总是非空的.

It's a trick to ensure you don't get an empty string in the substitution if one of the variables is empty. By putting x on both sides it's the same as just comparing the variables directly but the two sides will always be non-empty.

这是一个古老的混杂,当脚本被编写为时更有意义:

It's an old kludge which made more sense when scripts were written as:

if [ x$USER != x$RUN_AS_USER ]

如果你只有 $USER 并且它是空的,那么你最终会得到

There if you just had $USER and it were empty then you could end up with

if [  != root ]   # Syntax error

使用 x 你会得到这个,这是更好的:

With the x you get this, which is better:

if [ x != xroot ]

然而,当变量被引用时 x 是不必要的,因为引号中的空字符串不会被完全删除.它仍然显示为令牌.于是

However, when the variables are quoted the x is unnecessary since an empty string in quotes isn't removed entirely. It still shows up as a token. Thus

if [ "$USER" != "$RUN_AS_USER" ]   # Best

是最好的写法.在两个变量都为空的最坏情况下,您会得到这是一个有效语句:

is the best way to write this. In the worst case with both variables empty you'd get this which is a valid statement:

if [ "" != "" ]

这篇关于“x$VARIABLE"中 x 的 shell 脚本目的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆