I am looking at a bash script and it has a statement like this in it:
if [ -e ${MY_VARIABLE} ]
What does the -e parameter do? Does it check if the variable exists?
CodePudding user response:
If this is supposed to be a shell script, then it is invalid. Either if test -e "${MY_VARIABLE}"
or if [ -e "${MY_VARIABLE}" ]
. -e
itself is an invalid command, but the test
/[
binary has such an option.
-e
checks if a file exists. From the man page:
-e
FILE
FILE exists
NB. Always quote your variables, otherwise your script will not run (properly) or might perform unintended actions if a variable's value expands to several words (put differently: your variable contains whitespace)
CodePudding user response:
No this command checks if a file of any type exists. Your variable is probably a string with a file path?
Print out the value of the variable to see if it is a path.
CodePudding user response:
if [ -e ${MY_VARIABLE} ]
does not check if the variable exists. (For that, use ${MY_VARIABLE?}
or ${MY_VARIABLE }
(or :?
and :
) depending on what you want to do.)
The [
command never sees the string MY_VARIABLE
. The shell parses the string ${MY_VARIABLE}
and passes its expansion to [
. If MY_VARIABLE is not set (or is the empty string), the shell invokes the command [ -e ]
and tests whether or not the string -e
is empty (it is not). If MY_VARIABLE is set and non-empty, then [
is executed with some arguments. if MY_VARIABLE did not contain any whitespace (more accurately, if it doesn't contain values in IFS), then [
sees exactly 3 arguments (-e
, the expanded value of ${MY_VARIABLE}
, and ]
) and checks if the path named by the second argument exists in the file system. If MY_VARIABLE does contain elements of IFS, then [
gets more than 3 arguments and (probably) emits an error message complaining about unexpected arguments. (It is not necessarily an error if $MY_VARIABLE is subject to field splitting. For example, if ${MY_VARIABLE} expands to the string / -a -e /etc
, then [
will be invoked with the arguments -e
,/
, -a
, -e
, /etc
, and ]
and will check if /
and /etc
exist in the filesystem.)
Much of the behavior described above is rightly considered obscure, and is one of the primary reasons that best practice encourages the use of double quotes; if [ -e "${MY_VARIABLE}" ]
is one of the preferred ways to check if the file named in $MY_VARIABLE exists.