为什么bash告诉我在运行以下代码时找不到命令if? [英] why does bash tell me that the command if is not found when I run the following code?
问题描述
if [! -d / home / $ USER / testfoo];然后是mkdir / home / $ USER / testfoo; fi
如果目标testfoo不存在,会产生预期效果
但是
TESTCMD =if [!-d / home / $ USER / testfoo] ;然后是mkdir / home / $ USER / testfoo; fi
$ TESTCMD
返回
if:command not found
我做错了什么?
如果你使用变量作为这样的命令,它将变量的内容解释为命令的名称,而不是作为其参数后面的命令。
所以,如果你做 VAR = foo bar
然后 $ VAR
它会查找名为 foo bar的可执行文件(或内置文件)
,不适用于使用参数 bar
调用的名为 foo
的可执行文件。
要做你想做的事,你需要定义一个函数:
TESTCMD( ){
如果[! -d / home / $ USER / testfoo]
然后
mkdir / home / $ USER / testfoo
fi
}
TESTCMD
sorry, I am relatively new to bash, but
if [ ! -d /home/$USER/testfoo ]; then mkdir /home/$USER/testfoo; fi
has the desired effect of making a directory testfoo if it does not exist
but
TESTCMD="if [ ! -d /home/$USER/testfoo ]; then mkdir /home/$USER/testfoo; fi"
$TESTCMD
returns
if: command not found
What am I doing wrong?
If you use a variable as a command like this, it interprets the contents of the variable as the name of the command, not as a command followed by its arguments.
So if you you do VAR="foo bar"
and then $VAR
it looks for an executable (or built-in) called foo bar
, not for an executable called foo
that it calls with the argument bar
.
To do what you want, you need to define a function:
TESTCMD() {
if [ ! -d /home/$USER/testfoo ]
then
mkdir /home/$USER/testfoo
fi
}
TESTCMD
这篇关于为什么bash告诉我在运行以下代码时找不到命令if?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!