[英]Bash Script compare strings and variable in an if statement
I am trying to get a variable to compare to a string, and then do something if it does and go on to the next, but when i look at it in debug mode, the variable just shows up as ''
with nothing in it. 我正在尝试获取一个变量以与字符串进行比较,如果可以,请执行一些操作,然后继续执行下一个操作,但是当我在调试模式下查看该变量时,该变量只是显示为''
其中没有任何内容。
#!/bin/bash
echo -e "Enter the name of the document you wish to edit:\c"
read dname
CTYPE= file "$dname" | cut -d\ -f2
echo $CTYPE
VAR="ASCII"
VAR2="cannot"
if [ "$CTYPE" == "$VAR" ]
then
vi $dname
fi
I get this result: 我得到这个结果:
+ VAR=ASCII
+ VAR2=cannot
+ '[' '' == ASCII ']'
Where the ''
is empty even though I echo
d it and see that it is not empty. 凡''
是空的,即使我echo
ð它,看看它是不是空的。
I have tried it like these other ways as well, and get the same or similar non working result: 我也像其他方法一样尝试过它,并得到相同或相似的无效结果:
CTYPE= file "$dname" | cut -d\ -f2
if [ "$CTYPE" == "$VAR" ]
ctype= file "$dname" | cut -d\ -f2
if [ $ctype = "ASCII" ]
ctype= file "$dname" | cut -d\ -f2
if [ "$ctype" = "ASCII" ]
ctype= file "$dname" | cut -d\ -f2
if [ "$ctype" == "ASCII" ]
Not sure what I am missing, I've read so many posts I don't know where to go from here. 不确定我缺少什么,我已经读了很多帖子,我不知道从这里去哪里。 Thank you! 谢谢!
You have an error with CTYPE: 您有CTYPE错误:
CTYPE=$(file "$dname" | cut -d\ -f2)
You cannot have any spaces between the =
and the assignment. 你可以没有之间的任何空间=
和分配。 Further, you want the return from file "$dname" | cut -d\\ -f2
此外,您希望从file "$dname" | cut -d\\ -f2
返回 file "$dname" | cut -d\\ -f2
so you will have to enclose it in $()
or with backticks. file "$dname" | cut -d\\ -f2
因此您必须将其括在$()
或反引号中。
When you run this command: 运行此命令时:
d= date
bash does this: set an environment variable d
(with the value the empty string) only for the duration of the date
command. bash这样做: 仅在date
命令期间设置一个环境变量d
(值为空字符串)。 This is densely documented here . 这在这里被大量记录。
As David tells you, to capture the outut of a command, you need 正如David告诉您的那样,要捕获命令的输出,您需要
d=$(date)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.