0

I have the following code to detect if a file exist:

#!/bin/bash
VAR="/home/$USER/MyShellScripts/sample.txt"
if [ -e '$VAR' ]
        then
                echo "$VAR exist"
        else
                echo "the file $VAR doesn't exist!"
fi

if [ -x '$VAR' ]
        then
                echo "You have permissions to execute the file $VAR"
        else
                echo "You do not have permissions to execute the file $VAR"
fi

When I apply the ls command on the specified directory I see:

MyLAPTOP:~/MyShellScripts$ ls
exercise_4.sh  exercise_4Original.sh  first.sh  sample.txt  second.sh

So, if the file exists in the specified directory, why it is not detected? Below the script output:

MyLAPTOP:~/MyShellScripts$ ./exercise_4.sh
the file /home/username/MyShellScripts/sample.txt doesn't exist!
You do not have permissions to execute the file /home/username/MyShellScripts/sample.txt
rcmv
  • 151
  • 2
  • 3
  • 14
  • 6
    Because you're using single quotes (`'$VAR'`). – vanza Jun 28 '19 at 17:58
  • 1
    Possible duplicate of [Expansion of variable inside single quotes in a command in Bash](https://stackoverflow.com/q/13799789/608639), [How to echo variable inside single quotes using Bash?](https://stackoverflow.com/q/29351101/608639), etc. – jww Jun 28 '19 at 18:24

2 Answers2

4

Thats because you are using '$VAR' instead of "$VAR" in your if. Try "$VAR" instead. The $VAR within single quotes ('') will be interpreted as an normal string and not resolved to your variable.

To see the difference, try the following:

input          output
-------------- --------------------------------------------------
echo "$VAR"    /home/<your_username>/MyShellScripts/sample.txt
echo '$VAR'    $VAR
cxw
  • 16,685
  • 2
  • 45
  • 81
Futureman2007
  • 161
  • 10
2

`` means do not expand variables.

So this script checks file named '~/MyShellScripts/$VAR'. Not '"/home//MyShellScripts/sample.txt"'

Test.sh:

#!/bin/bash
VAR="Test"
echo $VAR
echo "$VAR"
echo '$VAR'

Result:

$ ./Test.sh
Test
Test
$VAR
Hikaru
  • 86
  • 1
  • 7