简体   繁体   中英

$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.

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, eg, this discussion at the bash-hackers wiki . Happy hacking!

Bash uses > to redirect the standard output stream to a file (instead of outputting it in your terminal). Likewise it uses < to take standard input from a file rather than from what you type (or pipe) into the terminal.

Use quoting to avoid this special treatment. Variable substitution is performed on double quoted strings, too, so you can pass the whole output as a single argument to echo , as cxw suggested :

echo "$1 < $2"

or you can pass 3 arguments:

echo $1 "<" $2
# or
echo $1 '<' $2

In single-quoted strings, no variable substitution is performed, so

echo '$1 < $2'

would not work as expected and instead output literally

$1 < $2

without replacing the variable names by the variables' content.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM