insidesin
insidesin

Reputation: 753

How do I tell if a variable is a file in bash

I am not a great bash scripter and hence have a few questions. One of which is how (or even whether) bash understands that a variable is a "file" or simply a local variable.

file=/usr/share/lib

Obviously this is a file to be saved, etc and can be used like so:

echo "$output" > $file

To save the output of $output to $file.

But where in bash does it calculate whether it's a file or not, is it only a file once it's been passed to a 'writing method'?

Upvotes: 1

Views: 104

Answers (3)

Toby Speight
Toby Speight

Reputation: 30940

Variables are strings - nothing more, nothing less. (I'm ignoring array variables here, WLOG).

Bash (or any shell) expands variables blindly, without considering what you intend to do with them. It's only in the next stage of command processing that the contents of the string matter.

To use your example:

output="foo bar"
file=/usr/share/lib
echo "$output" >"$file"

(I've quoted $file even though it's not necessary here, simply because I've been bitten too many times by changing the value and breaking everything).

The line

echo "$output" >"$file"

gets transformed into

echo "foo bar" >"/usr/share/lib"

and only then does bash consider the > and attempt to open /usr/share/lib for writing.

Upvotes: 0

arco444
arco444

Reputation: 22861

You need to check this yourself, bash is only aware of the contents of the variable. If you want to check if a file location is held within a variable, you can test for it using the -f test operator

if [ -f "$file" ]
then
  echo "$file is a file"
  echo "$output" > "$file"
else
  echo "$file is not a file"
fi

Upvotes: 3

Brian Agnew
Brian Agnew

Reputation: 272397

If you treat that variable as a file name, bash will simply do what it's told e.g.

echo "Test output" > $file

will work regardless of file being set to /tmp/myfile.txt, or to abcd. In the above you're using bash's file redirection to write out the standard out to the file you've named.

Consequently if you use the wrong variable in the above pattern, or have the value set incorrectly, bash will simply follow your instructions and you may end up with incorrectly named/located files.

Upvotes: 2

Related Questions