在If-Else语句中重定向回显时,Shell脚本显示错误消息

时间:2018-03-13 11:36:10

标签: linux shell if-statement

我正在尝试将输出重定向到if-else语句中的文件,但它不能与我合作。这就是我正在做的事情

$1=1    
output="/home/file.txt" 
if [[ $1 -gt 5 ]] 
then 
echo "$1 is greater than 5" > $output #this is working with me 
else 
echo "$1 is not greater than 5" > $output #this is giving me "ambiguous redirect" 
fi 

知道问题可能是什么?我尝试在双引号之间输入$ output,但是我收到了一条不同的错误消息:

if [[ $1 -gt 5 ]] 
then 
echo "$1 is greater than 5" > "$output" #this is working with me 
else 
echo "$1 is not greater than 5" > "$output" #this is giving me "No such file or directory" 
fi 

1 个答案:

答案 0 :(得分:-1)

首先,永远不要在你的脚本中使用$ 1到$ 9作为变量(也永远不要用$声明变量)。这些是Unix / Linux系统变量,这些变量由Unix / Linux用于存储命令行参数:

例如: -

    yourshellscript.sh hello word!

    echo $1" "$2 # this will print hello world!

我修改了适合您的脚本

#!/bin/bash  
#always put this line at the top of your shell script this indicate in 
#which shell this script should run in this case it is bash shell. This is 
#very important because each shall has different syntax for if, while 
#condition and numeric expression.
NUMBER=1
output="/home/file.txt"
if [ $NUMBER -gt 5 ]
then
    echo "$NUMBER is greater than 5" > $output #this is working with me
else
    echo "$NUMBER is not greater than 5" > $output #this is giving me "ambiguous redirect"
fi

您也可以从以下领事馆输入一个号码: -

NUMBER=1
read -p "Enter a Number : " NUMBER     
output="/home/file.txt"
if [ $NUMBER -gt 5 ]
then
    echo "$NUMBER is greater than 5" > $output #this is working with me
else
    echo "$NUMBER is not greater than 5" > $output #this is giving me "ambiguous redirect"
fi
相关问题