0

I am trying to redirect the output to a file within if-else statements but it is not working with me. Here's what I am doing

$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 

Any idea what the issue may be? I tried puting $output between double quotes, but I got a different error message:

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 
Dr.Bake
  • 141
  • 4
  • 18
  • 1
    Possible duplicate of [Getting an "ambiguous redirect" error](https://stackoverflow.com/questions/2462385/getting-an-ambiguous-redirect-error) – Ikaros Mar 13 '18 at 13:00
  • Can you verify that you get this error with the code as posted? It looks like you modified the script before posting, but didn't check that the error is still the same – that other guy Mar 13 '18 at 15:25

1 Answers1

-1

First of all never use $1 till $9 as variable in your script (also never declare variable with $). These are Unix/Linux system variable and these variable use by Unix/Linux to store the command line parameters:

For example:-

    yourshellscript.sh hello word!

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

I have modified your script which will work for you

#!/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

Also you can enter a number from consul like below:-

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
Abhijit Pritam Dutta
  • 5,521
  • 2
  • 11
  • 17