Search code examples
bashio-redirectionquoting

$2: No such file or directory


My code is:

#!/bin/bash
if [ $1 -gt $2 ];then
    echo $1 > $2
fi
if [ $1 -eq $2 ];then
    echo $1 = $2
fi
if [ $1 -lt $2 ];then
    echo $1 < $2
fi

On executing the script by ./script.sh 3 56 the response I got was ./script.sh: line 9: 56: No such file or directory. I have the permission to execute the script. I am new to bash programming and using linux. Please tell me how to fix my script.


Solution

  • echo $1 < $2 is a redirection that causes echo to read its input from the file whose name is in $2. Since a file called 56 doesn't exist, you get the error. To fix this, quote the string to print:

    echo "$1 < $2"
    

    Edit Welcome to the world of bash! While you're learning, I recommend using double-quotes around all uses of variables. This will save you some headaches up front, and you can learn the situations when you don't use quotes later. See, e.g., this discussion at the bash-hackers wiki. Happy hacking!