How do you use a command line argument as a file path and check for file existence in Bash?
I have the simple Bash script test.sh
:
#!/bin/bash
set -e
echo "arg1=$1"
if [ ! -f "$1" ]
then
echo "File $1 does not exist."
exit 1
fi
echo "File exists!"
and in the same directory, I have a data
folder containing stuff.txt
.
If I run ./test.sh data/stuff.txt
I see the expected output:
arg1=data/stuff.txt
"File exists!"
However, if I call this script from a second script test2.sh
, in the same directory, like:
#!/bin/bash
fn="data/stuff.txt"
./test.sh $fn
I get the mangled output:
arg1=data/stuff.txt
does not exist
Why does the call work when I run it manually from a terminal, but not when I run it through another Bash script, even though both are receiving the same file path? What am I doing wrong?
Edit: The filename does not have spaces. Both scripts are executable. I'm running this on Ubuntu 18.04.